[英]Minimizing the Height of a Binary Search Tree
If I am attempting to minimize the height of a Binary Search Tree, are these the correct steps?: 如果我试图最小化二叉搜索树的高度,这些是正确的步骤吗?:
1) produce a sorted array from the tree 2) reconstruct the tree by adding the sorted elements into the tree inorder 1)从树中生成排序后的数组2)通过将排序后的元素添加到树中来重构树
Adding an already sorted list to a simple non-balancing binary search tree will build the theoretical Worst case for a binary search tree. 将已经排序的列表添加到简单的非平衡二进制搜索树中,将为二进制搜索树建立理论上最差的情况。 The lowest-valued node is the root, every node is added to the 'right' of the node immediately preceding it in the list, and you create a tree of maximum depth, searching in O(n) time rather than O(lg n).
值最低的节点是根,每个节点都添加到列表中紧接其前的节点的“右侧”,然后创建最大深度的树,以O(n)时间而不是O(lg n )。 You'dd effectively just be building an overly complicated linked-list.
您实际上只是在构建一个过于复杂的链表。
对元素进行排序之后,可以通过将中间元素定义为根节点来重建树,然后分别从中间元素之前和之后的元素递归地构建左右子树。
I think if you reconstruct the tree structure before you try to insert sorted elements via inorder
, the solution you provide will be right. 我认为,如果您在尝试通过
inorder
插入排序元素之前重构树结构,那么您提供的解决方案将是正确的。
For example, if the original tree is like this: 例如,如果原始树是这样的:
(5)
(3) (6)
(2) (4)
(1)
Reconstruct the tree like this: 像这样重建树:
() () () () () ()
Insert sorted element via inorder
: 1, 2, 3, 4, 5, 6 通过插入排序元件
inorder
1,2,3,4,5,6:
(4) (2) (6) (1) (3) (5)
I suppose you have access to the tree and can alter it "manually". 我想您可以访问该树,并且可以“手动”更改它。 I think your balancing problem could be solved like this (pseudocode):
我认为您的平衡问题可以这样解决(伪代码):
depth(node)
{
if node is null, return 0;
l = depth(left child);
r = depth(right child);
diff = (r - l);
if (diff < -1) rotate right (as often as you need);
else if (diff > 1) rotate left (as often as you need);
return the new maximum depth of both subtrees +1;
}
I must confess, I am not very sure about this, but the idea is that you don't need the temporary array, because traversing the tree and applying the right rotations should do. 我必须承认,我对此不太确定,但想法是您不需要临时数组,因为遍历树并应用正确的旋转应该可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.