【问题标题】:Java - Mirror Image of a binary tree using recursionJava - 使用递归的二叉树的镜像
【发布时间】:2012-10-14 18:23:49
【问题描述】:

我正在为二叉树编写镜像方法。我的类的工作方式是我有一个抽象类 BinaryTree,它有子类 EmptyTree 和 ConsTree。我在为 ConsTree 编写方法时遇到问题。这个类看起来像这样:

public class ConsTree<T> extends BinaryTree<T>
{
    BinaryTree<T> left;
    BinaryTree<T> right;
    T data;

    public BinaryTree<T> mirrorImage() 
    {
        ConsTree<T> tree = new ConsTree<T>(this.data, this.right, this.left); //In the constructor, the second parameter sets the left tree, so creates a new tree with the left and right trees swapped
        if(this.left == null && this.right == null)
                return tree;
        if(this.left == null)
                return tree + this.right.mirrorImage();
        else if(right == null)
                return tree + this.left.mirrorImage();

        return tree + this.left.mirrorImage() + this.right.mirrorImage();
}

显然这不起作用,因为我不能对 BinaryTree 对象使用“+”运算符,但这是我想要完成的基本思想。我只是对如何将树木组合在一起有点困惑。任何帮助表示赞赏。谢谢。

【问题讨论】:

    标签: java recursion tree


    【解决方案1】:

    我认为BinaryTree 没有mirror 方法。

    在这种情况下,你的返回类型不应该是BinaryTree&lt;T&gt;,而是ConstTree&lt;T&gt;,因为你需要分支来实现mirrorImage()

    我觉得令人费解的是,在您拥有分支镜像之前,您在构造函数中将分支分配给返回的树。逻辑是

    1) 获取左右分支的镜像

    2) 用镜像创建一棵树。

    你正在设置一些你永远不会在那里使用的值。

    【讨论】:

      【解决方案2】:

      你想如何同时返回树和正确的mirrorImage!?简单,返回

          this.right.mirrorImage();
          this.left.mirrotImage();
      

      而不是

          tree + this.right.mirrorImage();
          tree + this.left.mirrorImage();
      

      【讨论】:

        【解决方案3】:
        public class BinaryTreeMirror {
        
            public static TreeNode mirrorOf(TreeNode rootNode) {
                if (rootNode == null) {
                    return rootNode;
                } else {
                    TreeNode temp = rootNode.right;
                    rootNode.right = rootNode.left;
                    rootNode.left = temp;
                    mirrorOf(rootNode.right);
                    mirrorOf(rootNode.left);
                }
                return rootNode;
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2020-03-16
          • 2021-01-30
          • 2010-12-07
          • 1970-01-01
          • 2015-10-02
          • 1970-01-01
          • 1970-01-01
          • 2016-07-20
          • 2013-07-20
          相关资源
          最近更新 更多