#701
Insert into a Binary Search Tree
MediumTreeBinary Search TreeBinary TreeBinary Search TreeTree Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses the properties of a BST to directly find the correct position for the new value without unnecessary traversals. This ensures we maintain the BST structure efficiently.
⚙️
Algorithm
5 steps- 1Step 1: Start from the root of the BST.
- 2Step 2: Compare the new value with the current node's value.
- 3Step 3: If the new value is less, move to the left child; if greater, move to the right child.
- 4Step 4: Continue until you find a null position where the new value can be inserted.
- 5Step 5: Insert the new value at the found null position.
solution.py25 lines
1# Full working Python code
2class TreeNode:
3 def __init__(self, val=0, left=None, right=None):
4 self.val = val
5 self.left = left
6 self.right = right
7
8def insertIntoBST(root: TreeNode, val: int) -> TreeNode:
9 if not root:
10 return TreeNode(val)
11 current = root
12 while True:
13 if val < current.val:
14 if current.left:
15 current = current.left
16 else:
17 current.left = TreeNode(val)
18 break
19 else:
20 if current.right:
21 current = current.right
22 else:
23 current.right = TreeNode(val)
24 break
25 return rootℹ
Complexity note: The time complexity is O(n) in the worst case for a skewed tree, but the space complexity is O(1) since we are using iterative traversal without additional data structures.
- 1Understanding the properties of BSTs allows for efficient insertion.
- 2Iterative approaches can reduce the risk of stack overflow in deep trees.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.