【发布时间】:2013-05-03 08:44:33
【问题描述】:
由于某种原因 add(value) 函数不想工作。我应该能够使用 Node 和 TreeNode 来创建一个孩子。这不是一棵平衡的树。我尝试了 Node 和 NodeTree 并使用节点创建变量并将其添加但没有成功
public abstract class TreeNode implements Comparable<TreeNode>{
protected int value;
protected TreeNode left;
protected TreeNode right;
public abstract int getValue();
public abstract int getSize();
public abstract TreeNode getLeft();
public abstract TreeNode getRight();
public void add(int value){
if (value >= this.value){
if (this.right == null){
this.right = new Node(value); //trying to put a node in the "right"
}else{
right.add(value);
}
}else if(value < this.value){
if (this.left == null){
this.left = new Node(value); //trying to do the same thing here
}else{
left.add(value);
}
}
}
public String toString() {
return (left.toString() + ", " +Integer.toString(this.value) + ", " + right.toString());
}
public int CompareTo(TreeNode obj){
if(this.value > obj.value){
return 1;
}else if(this.value < value){
return -1;
}else{
return 0;
}
}
//public void remove(int value) throws NotFoundException{
//}
}
【问题讨论】:
-
您输入的是什么值?您期望会发生什么以及实际发生了什么?在构造函数中分配的值在哪里?
-
你说你试过
Node和NodeTree。你试过TreeNode吗?
标签: java tree treenode addchild