0
votes

I have some questions about certain placement of child nodes since I'm just learning BSTs and it's quite confusing even after reading some sources and doing some online insertion applets. Let's say I want to add nodes 5,7,3,4 to an empty basic BST.

 add 5

  5  

 add 7

   5
      7   

 add 3

   5

3     7

 add 4

   5

3     7

  4

Ok I understand that the left child must be less than the parent AND less than or equal to the right child from that same parent. I follow it until we add the 4 node. How do we determine that the insertion of 4 goes to the bottom right leaf position of 3 instead of the bottom left leaf position? Also, doing a AVL insertion of nodes 5,18,3,7,11 yielded some surprising position placements. Inserting the fourth node, 7, went down through 18 instead of 3. Is there a particular reason why? Assuming that is the correct way, inserting 11 would switch the 11 and 18 spots, but wouldn't having 18 as the parent node, 7 as left child, and 11 as right child adhere to the principle of left child smaller than parent and smaller or equal to right child? I'm confused! I would appreciate any help. Thank you!

insert 7

 5

3 18

 7

insert 11

 5

3 11

 7 18
1

1 Answers

0
votes

In BSTs, elements in the left (right) subtree of any node are all less (greater) than the parent of the root of the subtree. So, in the left subtree of 5, both 3 and 4 are less than 5. Now look at 3. The reason 4 goes to the right, is because 4 is bigger than 3, so it goes right.

Same for your AVL question. 7 became the left child of 18, instead of the right child of 3 because 5 is the root. When doing an insert, you compare elements one level at a time. "Is 7 bigger than 5 (root)? Yes, go right. Is 7 bigger than 18? No, go left. No node to compare to, so 7 goes here".

Having 11 as the right child would not fit into a BST. 11 is smaller than 18, so it should be in the left subtree rooted at 18.