algo_052.md (860B)
1 # algo_052 2 3 ### Problem Statement 4 5 > Write an algorithm to insert a node (an element) into a Binary Search Tree (BST). 6 7 ## Algorithm 8 ``` 9 procedure insert_BST(root, val) 10 begin 11 nptr ← getNode(); 12 INFO(nptr) ← val; 13 LC(nptr) ← NULL; 14 RC(nptr) ← NULL; 15 if (root = NULL) then 16 root ← nptr; 17 return(root); 18 endif 19 ptr ← root; 20 parent ← NULL; 21 while (ptr ≠ NULL) do 22 parent ← ptr; 23 if (val < INFO(ptr)) then 24 ptr ← LC(ptr); 25 else if (val > INFO(ptr)) then 26 ptr ← RC(ptr); 27 else 28 write("Duplicate value not allowed"); 29 delete(nptr); 30 return(root); 31 endif 32 endwhile 33 if (val < INFO(parent)) then 34 LC(parent) ← nptr; 35 else 36 RC(parent) ← nptr; 37 endif 38 return(root); 39 end procedure 40 ```