构建平衡二叉搜索树
有没有什么方法可以构建一个平衡的二叉搜索树?
举个例子:
1 2 3 4 5 6 7 8 9
5
/ \
3 etc
/ \
2 4
/
1
我在想,应该有一种方法可以做到这一点,而不需要使用更复杂的自平衡树。否则我可以自己来做,但可能有人已经做过了 :)
谢谢大家的回答!这是最终的Python代码:
def _buildTree(self, keys):
if not keys:
return None
middle = len(keys) // 2
return Node(
key=keys[middle],
left=self._buildTree(keys[:middle]),
right=self._buildTree(keys[middle + 1:])
)
3 个回答
2
把你的数据的中位数(或者更准确地说,就是离中位数最近的那个元素)作为树的根节点。然后继续这个过程,递归地进行下去。
5
这篇文章详细解释了:
在最佳时间和空间内进行树的重新平衡
http://www.eecs.umich.edu/~qstout/abs/CACM86.html
还有这里:
一次性二叉搜索树平衡:
Day/Stout/Warren (DSW) 算法
http://penguin.ewu.edu/~trolfe/DSWpaper/
如果你真的想要实时进行平衡,你需要一个自平衡的树。
如果你只是想建立一个简单的树,而不想麻烦去平衡它,只需在将元素插入树之前随机打乱这些元素的顺序即可。
10
对于每个子树:
- 找到子树的中间元素,把它放在树的顶部。
- 找到中间元素之前的所有元素,递归地用这个方法来构建左边的子树。
- 找到中间元素之后的所有元素,递归地用这个方法来构建右边的子树。
如果你先对元素进行排序(就像你例子中那样),那么找到子树的中间元素可以在固定的时间内完成。
这是一个构建一次性平衡树的简单算法。它并不是一个自我平衡树的算法。
这里有一些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();
}
}