701. Insert into a Binary Search Tree
Approach 1: Recursively insert into left or right parts
Time Complexity: O(logN) assuming balanced BST (Otherwise O(N) worst case where N is number of nodes)
Space Complexity: O(M) height of the stack (recursive call)
Approach 2: Iterative Approach 1
We iterate through the tree and each time eliminate half the tree based on the value of the current node we are on. If the value to be inserted is greater than current node's value we move to the right tree and vice versa. By the time we finish iterating like this we reach the position where the node is supposed to inserted. We insert it in it's position using the TreeNode prevParser
which stores the position of the parser one iteration behind i.e. the parent node
Time Complexity: O(logN) assuming balanced BST (Otherwise O(N) worst case where N is number of nodes)
Space Complexity: O(1)
Last updated