【问题标题】:convert Binary tree to Binary Search Tree inplace using C使用 C 将二叉树就地转换为二叉搜索树
【发布时间】:2011-07-24 23:48:04
【问题描述】:

在不使用任何额外空间的情况下将二叉树转换为二叉搜索树。我想出了以下算法,但它不起作用。

BTtoBST(节点 *root)

1.如果根为NULL返回

2.else current=root

3.if (current->left > current) swap(current->left , current)

4.if (current->right right , current)

5.current=current->左

如果当前为 6 则转到 3!=NULL 否则转到 4

7.current=current->正确

提前致谢

PS:我看到了这个链接,但没有太大帮助! Convert Binary Tree -> BST (maintaining original tree shape)

【问题讨论】:

    标签: c binary-tree binary-search-tree in-place


    【解决方案1】:

    您可以像在 AVL 树 http://en.wikipedia.org/wiki/AVL_tree 中一样交换节点,包括子树(不仅是节点内容)

    只要违反 BST 约束就继续交换,每次交换后从根目录重新开始深度优先搜索。

    【讨论】:

      【解决方案2】:

      对树执行后序(自下而上)遍历,获取访问过的节点并将它们插入 BST。

      “没有任何额外空间”是否排除递归?

      如果不是,则类似:

      # 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是过滤操作;它需要一个现有的 bst 并返回一个添加了给定节点的新 bst。

      将叶节点添加到bst 是安全的,因为我们将永远不会再次访问它,因此我们可以覆盖其leftright 指针。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-28
        • 2017-03-30
        相关资源
        最近更新 更多