0
我正在处理用于插入到二叉搜索树中的代码。它适用于我插入的第一个节点,使其成为根,但在此之后它似乎不插入任何节点。我确定这是设置左/右引用的问题,但我无法弄清楚。请帮忙!用于二叉树的递归插入
//params: key of node to be inserted, parent node
public void insert(int newKey, TreeNode parent){
//if the root of the tree is empty, insert at root
if(this.getRoot() == null){
this.root = new TreeNode(newKey, null, null);
}
//if the node is null, insert at this node
else if(parent == null)
parent = new TreeNode(newKey, null, null);
else{
//if the value is less than the value of the current node, call insert on the node's left child
if(newKey < parent.getKey()) {
insert(newKey, parent.getLeft());
}
//greater than value of current node, call insert on node's right child
else if(newKey > parent.getKey()){
insert(newKey, parent.getRight());
}
//same as value of current node, increment iteration field by one
else if(newKey == parent.getKey())
parent.incrementIterations();
}
}
我的treenodes具有键,左,右,迭代字段以及getter/setter函数。 提前谢谢!
一个问题,我可以看到的是,父母是按值传递。对父母的更改将交给本地副本。您可能需要通过参考。 – 2014-10-09 04:20:29
是的,谢谢!我注意到,以及添加额外的if循环来解决它。我相信这能解决问题: 如果(则newkey
2014-10-09 04:29:59