我的有些形状的二叉树。我想将其转换为BST搜索相同形状的树。可能吗?
I have a binary tree of some shape. I want to Convert it to BST search tree of same shape. Is it possible?
我试过类似的方法 -
I tried methods like -
请在序遍历二叉树和放大器;把内容到一个数组。然后映射到这一个BST牢记条件(左VAL< =根< =右VAL)。这适用于某些情况下,但FAILE别人。P.S:我一看这 - http://stackoverflow.com/questions/741900/binary-trees-question-checking-for-similar-shape.不过,这很容易比较2 BST的相似性的形状。
P.S.: I had a look at this - http://stackoverflow.com/questions/741900/binary-trees-question-checking-for-similar-shape. But It's easy to compare 2 BST's for similarity in shape.
简短的回答是:你不能。一个BST要求节点按照留下的规则< =电流I对。在这个例子中,你链接:http://upload.wikimedia.org/wikipedia/commons/f/f7/Binary_tree.svg,如果你尝试建立与相同十八一个BST你会发现,你不能。
The short answer is: you can't. A BST requires that the nodes follow the rule left <= current < right. In the example you linked: http://upload.wikimedia.org/wikipedia/commons/f/f7/Binary_tree.svg, if you try and build a BST with the same shap you'll find that you can't.
不过,如果你想舒展BST的定义,它允许左&LT; =电流I =权(注意,这里电流I =右是允许的,作为并列的严格定义)就可以了。排序的所有元素,并把它们粘在数组中。现在做一个中序遍历,在节点与您的阵列中的每个元素替换值。下面是一些伪code:
However if you want to stretch the definition of a BST so that it allows left <= current <= right (notice that here current <= right is allowed, as apposed to the stricter definition) you can. Sort all the elements and stick them in an array. Now do an in-order traversal, replacing the values at nodes with each element in your array. Here's some pseudo code:
// t is your non-BST tree, a is an array containing the sorted elements of t, i is the current index into a
index i = 0
create_bst(Tree t, Array a)
{
if(t is NIL)
return;
create_bst(t->left, a)
t->data = a[i]
i++
create_bst(t->right, a)
}
结果不会但是真正的BST。如果你想有一个真正的BST这是尽量接近原来的形状成为可能,那么你再次把元素的有序数组,但这个时候将它们插入到BST。在您将它们插入的顺序由原树的子树的大小来定义。下面是一些伪code:
The result won't be a true BST however. If you want a true BST that's as close to the original shape as possible, then you again put the elements in a sorted array but this time insert them into a BST. The order in which you insert them is defined by the sizes of the subtrees of the original tree. Here's some pseudo-code:
// left is initially set to 0
create_true_bst(Tree t, BST bt, array a, index left)
{
index i = left + left_subtree(t)->size
bt->insert(a[i])
if(left_subtree(t)->size != 0)
{
create_true_bst(t->left, bt, a, left)
create_true_bst(t->right, bt, a, i + 1)
}
}
这将不能保证形状是一样的但是。
This won't guarantee that the shape is the same however.
上一篇:数组PHP数组排序数组、PHP