使用 C 将二叉树转换为二叉搜索树
不使用任何额外的空间将二叉树转换为二叉搜索树。我想出了以下算法,但它不起作用。
BTtoBST(node *root)
1.如果 root 为 NULL 返回
2.else current=root
3.if (current->left > current) swap(current->left , current)
4.if (current->current) ;right < current) swap(current->right , current)
5.current=current->left
6 如果 current!=NULL 则转到 3 否则转到 4
7.current=current->right
提前致谢
PS:我看到了这个链接,但没有多大帮助! 转换二叉树 -> BST(保持原始树形状)
Without using any extra space convert Binary Tree to Binary Search tree.I came up with the following algo but It doesn't work.
BTtoBST(node *root)
1.if the root is NULL return
2.else current=root
3.if (current->left > current) swap(current->left , current)
4.if (current->right < current) swap(current->right , current)
5.current=current->left
6 go to 3 if current!=NULL else go to 4
7.current=current->right
Thanks in advance
PS:I saw this link but was not of much help!!
Convert Binary Tree -> BST (maintaining original tree shape)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以像在 AVL 树 http://en 中一样交换包括子树在内的节点(不仅仅是节点内容)。 wikipedia.org/wiki/AVL_tree
只要违反 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
Just keep swapping as long as BST constraints are violated, restarting deep first search from root after each swap.
对树执行后序(自下而上)遍历,获取访问过的节点并将它们插入到 BST 中。
“没有任何额外空间”是否排除递归?
如果不是,那么类似:
bt_to_bst
是一个过滤操作;它需要一个现有的 bst 并返回一个新的 bst,其中添加了给定的节点。向
bst
添加叶节点是安全的,因为我们永远不会再访问它,因此我们可以覆盖它的left
和right
指针。Perform a post-order (bottom up) traversal of the tree, taking the nodes that are visited and inserting them into a BST.
Does "without any extra space" preclude recursion?
If not, then something like:
bt_to_bst
is a filtering operation; it takes an existing bst and returns a new one with the given node added to it.Adding a leaf node to the
bst
is safe because we will never visit it again, so we can overwrite itsleft
andright
pointers.