问题描述:

QUESTION : Design a mirror method that computes the mirror image of a binary

tree.

What is wrong with my code?? This makes sense to me, however the only example that passes is my Leaf only example:

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());

}

}

网友答案:

How is it not passing? I added some test methods and it seems to work

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());

        }
    }
}

And the output is:

1<->1

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

Isn't it mirrored?

相关阅读:
Top