当我在插入方法中添加一个名为“Bob”的节点时:
public void insert(String aLabel){
//left recursion:
if(this.getLabel().compareTo(aLabel) <= 0) {
if (childrenLeft == null) {
BSTreeNode aNode = new BSTreeNode(aLabel,this);
return;
}
else {
childrenLeft.insert(aLabel);
}
}
//right recursion
else {
if (childrenRight==null) {
BSTreeNode aNode = new BSTreeNode(aLabel,this);
return;
}
else{
childrenRight.insert(aLabel);
}
}
}
我的树只在左侧添加一个没有标签的空节点。 (BSTreeNode aNode = new BSTreeNode;)是否有问题?因为当我像这样硬编码节点时:
BSTreeNode Louis = new BSTreeNode("Louis", treeRoot);
BSTreeNode bonny = new BSTreeNode( "bonny", treeRoot);
BSTreeNode Sue = new BSTreeNode("Anne", bonny);
BSTreeNode Sam = new BSTreeNode("Sam",Louis);
BSTreeNode Anne2 = new BSTreeNode( "delta", bonny);
BSTreeNode Frank = new BSTreeNode("Kalle", Louis);
这个树展示了标签并且被插入到所需位置。其他的代码-构造函数:
public BSTreeNode( String aLabel,BSTreeNode aParent){
label = aLabel;
parent = aParent;
//add this node as a child of this node's parent either left or right
if(parent != null){
if(parent.getLabel().compareTo(label)<= 0) {
parent.addLeftChild(this);
}
if(parent.getLabel().compareTo(label)> 0) {
parent.addRightChild(this);
}
}
}
这是在节点创建时将节点添加到父节点的构造函数。添加childleft和childright方法:
private void addLeftChild(BSTreeNode aNode){
if(childrenLeft == null) this.childrenLeft = aNode;
}
private void addRightChild(BSTreeNode aNode) {
if(childrenRight == null) this.childrenRight = aNode;
}