【发布时间】:2018-11-22 03:13:00
【问题描述】:
我正在尝试编写一个递归方法来将节点添加到二叉搜索树(不允许重复)。出于某种原因,该方法仅在树为空时有效,否则它会打印出“重复”(即使它不是重复的)。我是编程新手,希望能得到解决此问题的帮助和提示。谢谢。
//add new node to the tree
public void add(int data) {
Node<Integer> newNode = new Node<>(data); //create new node with the data
//if the tree is empty, the newNode becomes the root
if (size() == 0) {
root = newNode;
return;
}
//otherwise, check if node should be placed to right or left
add(data, root);
}
private void add(int data, Node<Integer> node) {
//base case - found an empty position
if (node == null) {
node = new Node<Integer>(data);
}
if (data < node.data) {
add(data, node.left);
}
else if (data > node.data) {
add(data, node.right);
}
else if (data == node.data) {
System.out.println("Duplicate. This value cannot be added to the tree.");
}
}
【问题讨论】:
标签: java tree binary-tree binary-search-tree binary-search