问题:设计一种计算二进制镜像的镜像方法 树。
我的代码出了什么问题?这对我来说很有意义,但唯一的例子就是我的Leaf唯一例子:
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());
}
}
答案 0 :(得分: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}}&LT; - 大于0,{23,{3},{2}},{1}
是不是镜像了?