好的,所以我目前正在尝试创建一个二叉搜索树,每个节点都包含对某个对象的引用,以及对其左子节点的引用和对其右子节点的引用(总共 3 个变量)。左孩子必须总是比它的父母小,而右孩子总是必须比它的父母大。我必须创建两个方法:1 方法 ( contains()) 检查元素是否在树中,以及 add() 方法将元素添加到树中的适当位置。
这是 BinarySearchTree 类:
public class BinarySearchTree extends BinaryTree {
public BinarySearchTree(TreeNode t){
super(t);
}
public boolean contains (Comparable obj){
if (this.myRoot != null){
return containshelper(obj, this.myRoot);
}
return false;
}
public static boolean containshelper(Comparable comp, TreeNode t){
boolean flag = true;
int x = comp.compareTo(t.myItem);
if (x < 0 && t.myLeft != null){
containshelper(comp,t.myLeft);
}
if (x > 0 && t.myRight != null){
containshelper(comp,t.myRight);
}
if (x == 0){
return true;
}
return false;
}
public void add(Comparable key) {
if (!this.contains(key)){
if (this.myRoot != null){
add(myRoot, key);
}
System.out.print("Getting Here ");
}
else {
System.out.print("Tree already contains item");
}
}
private static TreeNode add(TreeNode t, Comparable key) {
if (((Comparable) t.myItem).compareTo(key) < 0 && t.myLeft != null){
add(t.myLeft,key);
}
if(((Comparable) t.myItem).compareTo(key) > 0 && t.myRight != null ) {
add(t.myRight,key);
}
if (((Comparable) t.myItem).compareTo(key) < 0 && t.myLeft == null){
TreeNode q = new TreeNode(key);
t.myLeft = q;
}
if (((Comparable) t.myItem).compareTo(key) > 0 && t.myRight == null ){
TreeNode w = new TreeNode(key);
t.myRight = w;
}
return t;
}
}
这是 TreeNode 类(包含在 BinaryTree 中):
public static class TreeNode {
public Object myItem;
public TreeNode myLeft;
public TreeNode myRight;
public int size;
public TreeNode (Object obj) {
size = size(this);
myItem = obj;
myLeft = myRight = null;
}
public int size(TreeNode t) {
return(sizehelper(t));
}
private int sizehelper(TreeNode node) {
if (node == null){
return(0);
}
else {
return(size(node.myLeft) + 1 + size(node.myRight));
}
}
public TreeNode (Object obj, TreeNode left, TreeNode right) {
myItem = obj;
myLeft = left;
myRight = right;
}
}
}
我很确定我的 contains() 方法有效,但是对于我的一生,我无法弄清楚为什么 add() 不起作用。任何帮助将不胜感激。