簡體   English   中英

Java-使用遞歸的二叉樹的鏡像

[英]Java - Mirror Image of a binary tree using recursion

我正在為二叉樹編寫鏡像方法。 我的類的工作方式是我有一個抽象類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對象使用'+'運算符,但這是我要完成的工作的基本概念。 我只是對如何將樹合並在一起感到困惑。 任何幫助表示贊賞。 謝謝。

您想如何同時返回樹和正確的mirrorImage !? 簡單地,返回

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

代替

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

我認為BinaryTree沒有mirror方法。

在這種情況下,你的返回類型不應該是BinaryTree<T>ConstTree<T>因為你需要的分支來實現mirrorImage()

我感到困惑的是,在擁有分支的鏡像之前,將分支分配給構造函數中的返回樹。 邏輯是

1)左右獲取分支的鏡像

2)創建帶有鏡像的樹。

您正在設置一些永遠不會在其中使用的值。

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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM