Insert into a BST
Problem
Imagine you are maintaining a sorted phone directory stored as a binary search tree. When a new contact is added, you need to insert it in the correct position to keep the directory organized.
Given the root node of a binary search tree (BST) and a value to insert into the tree, insert the value into the BST. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST. The insertion must maintain the BST property.
The number of nodes in the tree is in the range [0, 10^5].-10^8 <= Node.val <= 10^8All the values Node.val are unique.val does not exist in the original BST.Edge cases: Empty tree (root = null) → new node becomes rootInsert value smaller than all existing nodes → inserted as leftmost leafInsert value larger than all existing nodes → inserted as rightmost leaf
Test Cases
t1_01basic
Input
{"root":[4,2,7,1,3],"val":5}Expected
[4,2,7,1,3,5]Starting at root 4, since 5 > 4, go right to 7. Since 5 < 7, insert 5 as left child of 7.
t1_02basic
Input
{"root":[10,5,15,null,null,12,20],"val":13}Expected
[10,5,15,null,null,12,20,null,null,null,13]Traverse from 10 to 15, then to 12; since 13 > 12, insert 13 as right child of 12.
