【发布时间】:2016-01-21 06:15:48
【问题描述】:
我正在为二叉树创建递归插入方法。此方法无法将节点添加到树中。我似乎找不到这种方法有什么问题。构造函数为子节点和父节点获取一个字符串标签。
public void insert(String aLabel) {
//if compare is positive add to right else add to left
//basis case:
BSTreeNode aNode = new BSTreeNode(aLabel,null);
if (aNode.parent == null) {
aNode.parent = this;
}
inserts(this,aNode);
}
private void inserts(BSTreeNode aParent, BSTreeNode aNode){
//initially the root node is the parent however a proper parent is found thorough recursion
//left recursion:
if(aParent.getLabel().compareTo(aNode.getLabel()) <= 0) {
if (this.childrenLeft == null) {
this.childrenLeft = aNode;
aNode.parent = this;
return;
} else {
childrenLeft.inserts(childrenLeft, aNode);
}
}
//right recursion
else {
if (this.childrenRight==null) {
this.childrenRight = aNode;
return;
}
else{
childrenRight.inserts(childrenRight,aNode);
}
}
}
【问题讨论】:
-
有什么问题?它只是没有生成正确的 BST 还是您遇到任何异常?您的第一个 if 子句的条件似乎是错误的。检查一下。您已检查父级是否较小
标签: java recursion binary-tree binary-search-tree nodes