0

问题:设计一种计算二叉树镜像的镜像方法。

我的代码有什么问题??这对我来说很有意义,但是唯一通过的例子是我的 Leaf only 例子:

abstract class ABT {

    public abstract ABT mirror(); 
    }

class Leaf extends ABT { 
    int val; 
    Leaf(int val){ 
        this.val = val; 
    }

public ABT mirror() { 
    return this; 
}
}

class Node extends ABT { 
    int data; 
    ABT left; 
    ABT right; 
    Node(int data, ABT left, ABT right) { 
        this.data = data; 
        this.left = left; 
        this.right = right; 
    }

public ABT mirror() { 
    return new Node(this.data, this.right.mirror(), this.left.mirror());

}

}

4

1 回答 1

0

怎么不通过?我添加了一些测试方法,它似乎工作

public class TreeTest {

    public static void main(String[] args){
        new TreeTest();
    }

    TreeTest(){
        Leaf one = new Leaf(1);
        Leaf two = new Leaf(2);
        Leaf three = new Leaf(3);
        Node node23 = new Node(23,two,three);
        Node root = new Node(0,one,node23);



        System.out.println(one+"<->"+one.mirror());
        System.out.println(root+"<->"+root.mirror());
    }

    abstract class ABT {

        public abstract ABT mirror();
    }

    class Leaf extends ABT {

        int val;

        Leaf(int val) {
            this.val = val;
        }

        public ABT mirror() {
            return this;
        }
        public String toString(){
            return Integer.toString(val);
        }
    }

    class Node extends ABT {

        int data;
        ABT left;
        ABT right;

        Node(int data, ABT left, ABT right) {
            this.data = data;
            this.left = left;
            this.right = right;
        }

        public String toString(){
            StringBuilder sb = new StringBuilder();
            sb.append(data).append(",{").append(left.toString()).append("},{")
                    .append(right.toString()).append("}");
            return sb.toString();

        }
        public ABT mirror() {
            return new Node(this.data, this.right.mirror(), this.left.mirror());

        }
    }
}

输出是:

1<->1

0,{1},{23,{2},{3}}<->0,{23,{3},{2}},{1}

不是镜像吗?

于 2013-05-16T04:50:41.140 回答