简体   繁体   English

使用C将二进制树转换为就地二进制搜索树

[英]convert Binary tree to Binary Search Tree inplace using C

Without using any extra space convert Binary Tree to Binary Search tree.I came up with the following algo but It doesn't work. 没有使用任何额外的空间,将Binary Tree转换为Binary Search tree。我想出了以下算法,但它不起作用。

BTtoBST(node *root) BTtoBST(节点*根)

1.if the root is NULL return 1.如果根为NULL返回

2.else current=root 2.else current = root

3.if (current->left > current) swap(current->left , current) 3.如果(current-> left> current)交换(current-> left,current)

4.if (current->right < current) swap(current->right , current) 4.如果(current-> right <current)swap(current-> right,current)

5.current=current->left 5.当前=当前->左

6 go to 3 if current!=NULL else go to 4 如果current!= 6,则转到3; = NULL,否则转到4

7.current=current->right 7.current =当前->右

Thanks in advance 提前致谢

PS:I saw this link but was not of much help!! PS:我看到了此链接,但并没有太大帮助!! Convert Binary Tree -> BST (maintaining original tree shape) 转换二叉树-> BST(保持原始树形)

You can swap the nodes including subtrees (not only the node content) like in an AVL Tree http://en.wikipedia.org/wiki/AVL_tree 您可以像在AVL树中那样交换节点,包括子树(不仅是节点内容),如http://en.wikipedia.org/wiki/AVL_tree

Just keep swapping as long as BST constraints are violated, restarting deep first search from root after each swap. 只要违反了BST约束,就保持交换,每次交换后从根重新开始深度优先搜索。

Perform a post-order (bottom up) traversal of the tree, taking the nodes that are visited and inserting them into a BST. 对树执行后置(自下而上)遍历,获取要访问的节点并将其插入BST。

Does "without any extra space" preclude recursion? “没有任何多余空间”是否会阻止递归?

If not, then something like: 如果没有,则类似于:

# top level call passes null for bst
bt_to_bst (root, bst)
  # nothing to add to bst; just return it
  if null(root) -> return bst
  # if this is a leaf node, stick it into the BST
  if null(root->left) && null(root->right)
    return bst_insert(bst, root)
  # otherwise add all of left subtree into the bst and then the right tree
  bst = bt_to_bst (root->left, bst);
  return bt_to_bst (root->right, bst);

bt_to_bst is a filtering operation; bt_to_bst是过滤操作; it takes an existing bst and returns a new one with the given node added to it. 它需要一个现有的bst并返回一个添加了给定节点的新bst。

Adding a leaf node to the bst is safe because we will never visit it again, so we can overwrite its left and right pointers. 添加叶节点到bst是安全的,因为我们将永远不会再次访问它,这样我们就可以覆盖其leftright指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM