英文:
Issues with binary search tree
问题
I need some help to why an insertion in a bst doesn't work on the following code. Is there some concept on how java passes parameters that I do not know?
我需要帮助理解为什么在以下代码中二叉搜索树的插入不起作用。是否有关于Java参数传递的概念我不了解的地方?
英文:
I need some help to why an insertion in a bst doesn't work on the following code. Is there some concept on how java passes parameters that I do not know?
public void insert(int input){
insert(root, input);
}
private void insert(Node node, int input){
Node new_node = new Node(input);
if (node == null) {
node = new_node;
}
else if (input == node.data) {
System.out.println("input exists");
}
else {
if (input < node.data) {
insert(node.left, input);
}
else{
insert(node.right, input);
}
}
}
答案1
得分: 0
尝试在二叉搜索树中这样插入:
public void insert(int val) {
root = put(root, val);
}
private Node insert(Node node, int val) {
if (node == null)
return new Node(val);
int cmp = Integer.valueOf(val).compareTo(node.data);
if (cmp < 0)
node.left = insert(node.left, val);
else if (cmp > 0)
node.right = insert(node.right, val);
else
node.data = val;
return node;
}
英文:
Try to insert like this in the BST
public void insert(int val) {
root = put(root, val);
}
private Node insert(Node node, int val) {
if (node == null)
return new Node(val);
int cmp = Integer.valueOf(val).compareTo(node.data);
if (cmp < 0)
node.left = insert(node.left, val);
else if (cmp > 0)
node.right = insert(node.right, val);
else
node.data = val;
return node;
}
答案2
得分: 0
重新分配参数 node
不会改变你传递给方法的东西 (node.left
或 node.right
):
node = new_node;
因为 node
存储了对 Node
对象的引用(你想要替换的对象)。赋值只会改变引用,使其引用另一个对象。更多信息请参阅 此链接。
你可以重新分配 node.left
和 node.right
:
Node new_node = new Node(input);
if (input == node.data) {
System.out.println("input exists");
} else if (input < node.data) {
if (node.left != null) {
insert(node.left, input);
} else {
node.left = new_node;
}
}
else{
if (node.right != null) {
insert(node.right, input);
} else {
node.right = new_node;
}
}
英文:
Reassigning the parameter node
won't change anything about the thing you passed to the method (node.left
or node.right
):
node = new_node;
Because node
stores a reference to the Node
object (that you want to replace). The assignment only changes the reference so that it refers to another object. See this for more info.
You could reassign node.left
and node.right
instead:
Node new_node = new Node(input);
if (input == node.data) {
System.out.println("input exists");
} else if (input < node.data) {
if (node.left != null) {
insert(node.left, input);
} else {
node.left = new_node;
}
}
else{
if (node.right != null) {
insert(node.right, input);
} else {
node.right = new_node;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论