Hello,
I am new to Java and have a question I wonder if someone could please help?
I have the following code to insert into a binary tree :
I walked through this code and saw that when insert(Node node, int data) finally
returned from the recursion, it returned the node it just created and thus it
replaced the value of "root". But when I inserted some debugging statements to
print out the "data" of "root", I saw that the "data" of "root" never changed, which
was correct (and expected result).
I wonder if someone could tell me why the value of "root" never changed when
everytime insert(Node node, int data) was called, it returned a new "node".
Thank you very much in advance,
Akino
I am new to Java and have a question I wonder if someone could please help?
I have the following code to insert into a binary tree :
Code:
public void insert(int data) {
root = insert (root,data);
}
/* recursive helper */
private Node insert(Node node, int data) {
if (node == null)
node = new Node(data);
else if (data < node.data)
node.left = insert(node.left, data);
else
node.right = insert(node.right, data);
return (node);
}
returned from the recursion, it returned the node it just created and thus it
replaced the value of "root". But when I inserted some debugging statements to
print out the "data" of "root", I saw that the "data" of "root" never changed, which
was correct (and expected result).
I wonder if someone could tell me why the value of "root" never changed when
everytime insert(Node node, int data) was called, it returned a new "node".
Thank you very much in advance,
Akino
Comment