对于每个子树:
- 找到子树的中间元素,并将其放在树的顶部。
- 在中间元素之前找到所有元素,然后递归使用此算法来获取左侧的子树。
- 找到中间元素之后的所有元素,然后递归使用此算法来获取正确的子树。
如果您首先对元素进行排序(如您的示例中所示),则可以在恒定时间内找到子树的中间元素。
这是构造一次性平衡树的简单算法。它不是用于自平衡树的算法。
这是一些C#源代码,您可以自己尝试:
public class Program{ class TreeNode { public int Value; public TreeNode Left; public TreeNode Right; } TreeNode constructBalancedTree(List<int> values, int min, int max) { if (min == max) return null; int median = min + (max - min) / 2; return new TreeNode { Value = values[median], Left = constructBalancedTree(values, min, median), Right = constructBalancedTree(values, median + 1, max) }; } TreeNode constructBalancedTree(IEnumerable<int> values) { return constructBalancedTree( values.OrderBy(x => x).ToList(), 0, values.Count()); } void Run() { TreeNode balancedTree = constructBalancedTree(Enumerable.Range(1, 9)); // displayTree(balancedTree); // TODO: implement this! } static void Main(string[] args) { new Program().Run(); }}


