【发布时间】:2015-04-16 03:09:05
【问题描述】:
免责声明:这是针对我在家庭作业中遇到的问题。我需要重构我的 add 方法和 findnodelocation 方法,以便当 finddnodelocation 返回将添加新值的父节点时,它会继续并使用 add 方法将值添加到它需要去的二叉搜索树.
public void add(int val) {
/*Adds a new node to the binary tree after traversing the tree and figuring out where it belongs*/
Node nodeObjToAdd = new Node(val);
if(root == null){
//if node root is not null root = new node value
root = nodeObjToAdd;
}
Node nodeTraversed = root;
traverseAdd(nodeTraversed, nodeObjToAdd);
}
public Node findNodeLocation(Node focusNode, int val) {
/*returns where a new node with the given value will be placed based on the RootNode, and passed in value.*/
if(val < focusNode.value && focusNode.leftChild != null){
return focusNode.leftChild;
}
if(val >= focusNode.value && focusNode.rightChild != null){
return focusNode.rightChild;
}
else
return this.root;
}
【问题讨论】:
-
问题不清楚。你想返回什么?深度,价值?您所说的“我如何通过返回另一个 Node 对象来返回放置节点的位置”是什么意思。 ?
-
你想在哪里插入新节点?当第一个子节点为空时?
标签: java data-structures binary-search-tree nodes