1

I don't know why I need to assign node.left = insert(node.left, data) again, for I have assigned it using node = new BNode(data).

private BNode insert(BNode node, int data) { if (node == null) { node = new BNode(data); } else if (node.data < data) { node.left = insert(node.left, data); } else if (node.data > data) { node.right = insert(node.right, data); } return node; } 
6
  • I don't know the format to paste my code. So I paste it here. Commented Mar 21, 2016 at 2:12
  • private BNode insert(BNode node, int data) { if (node == null) { node = new BNode(data); } else if (node.data < data) { node.left = insert(node.left, data); } else if (node.data > data) { node.right = insert(node.right, data); } return node; } Commented Mar 21, 2016 at 2:13
  • I am really sorry, but it costs me an hour to adjust the format. Commented Mar 21, 2016 at 2:15
  • Lay off the boldface. It's just noise. Commented Mar 21, 2016 at 5:23
  • private void insert(BNode node, int data) { if (node.data < data) { if (node.right != null) { insert(node.right, data); } else node.right = new BNode(data); } else if (node.data > data) { if (node.left != null) { insert(node.left, data); } else node.left = new BNode(data); } } Commented Mar 21, 2016 at 6:18

1 Answer 1

1

In a Binary Search Tree you have to place any new elements in as leafs. Your code starts off by checking if we are currently looking at a node and if so, then insert our data here. Otherwise we need to continue down a branch until we reach a leaf. Therefore we call this function on the left or right branch (depending on the number and the data in the node). The way we do it is by calling the function on either node.left or node.right. If the child is a null, then we want to say that now our child is this new node that we just inserted.

If the child is not a leaf, then by returning the original child this assignment will do nothing. It only does something by saying

node = new BNode(data); 

and therefore the previous time this was called will be the only one that gets its left or right child changed to the current new leaf and all other left and right children remain the way they were.

Sign up to request clarification or add additional context in comments.

2 Comments

I understand it. node = new BNode(data) just creates a new BNode, which is nothing about the tree. So I have to connect this new node to the tree.
If this properly answers your question, can you accept the answer?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.