【问题标题】:Mirror Binary Search Tree using Recursion使用递归镜像二叉搜索树
【发布时间】:2020-03-16 19:25:03
【问题描述】:

在练习二叉搜索树时寻求帮助。我无法弄清楚我的代码哪里出错了,因为它似乎遵循通用递归格式。可能与临时节点或返回语句有关?任何帮助将不胜感激。

public static Node < Integer > mirror(Node < Integer > root) {

    if (root == null)
        return null;
    else {

        mirror(root.left);
        mirror(root.right);

        Node temp = root.left;
        root.left = root.right;
        root.right = temp;

        return root;

    }

} 

【问题讨论】:

  • 假设您正在搜索需要合并一些 if statement 的内容。然后继续遍历树,直到 if 计算结果为true,然后返回链上的值。您的树需要进行排序才能有效地工作。

标签: java recursion binary-tree


【解决方案1】:

首先,您似乎没有为属于镜像树的节点分配内存。注意指令

Node temp;

不在堆中分配,而是在堆栈中分配。当函数返回时,这块内存被释放,你在那里存储的任何东西都没有意义。

其次,您似乎没有很清楚的遍历模式,我认为是因为线

root.right = temp;

呈现出一种不对称性。

这是一种获取使用前序模式的镜像二叉树等方法(在 C++ 伪代码中):

Node * mirror(Node * root)
{
  if root == NULL
    return NULL;

  Node * mirror_root = new Node;
  mirror_root->left = mirror(root->right); // here is where the mirroring happens
  mirror_root->right = mirror(root->left);

  return mirror_root;
}

您可以尝试执行相同的操作,按后序或中序分配节点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-02
    • 2014-01-02
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 2019-04-17
    • 1970-01-01
    相关资源
    最近更新 更多