Java 二叉树比较函数实现:Compare 函数详解
public class Tree { private int value; private Tree left; private Tree right;
public Tree(int value) {
this.value = value;
this.left = null;
this.right = null;
}
public void insert(int value) {
if (value < this.value) {
if (this.left == null) {
this.left = new Tree(value);
} else {
this.left.insert(value);
}
} else if (value > this.value) {
if (this.right == null) {
this.right = new Tree(value);
} else {
this.right.insert(value);
}
}
}
public boolean compare(Tree oTree) {
if (oTree == null) {
return false;
}
if (this.value != oTree.value) {
return false;
}
boolean leftCompare = false;
boolean rightCompare = false;
if (this.left == null && oTree.left == null) {
leftCompare = true;
} else if (this.left != null && oTree.left != null) {
leftCompare = this.left.compare(oTree.left);
}
if (this.right == null && oTree.right == null) {
rightCompare = true;
} else if (this.right != null && oTree.right != null) {
rightCompare = this.right.compare(oTree.right);
}
return leftCompare && rightCompare;
}
}
原文地址: https://www.cveoy.top/t/topic/oE0t 著作权归作者所有。请勿转载和采集!