LeetCode #450 Delete Node in a BST
Problem
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.
Basically, the deletion can be divided into two stages:
- Search for a node to remove.
- If the node is found, delete the node.
Note: Time complexity should be O(height of tree).
Example:
root = [5,3,6,2,4,null,7]
key = 3 5
/ \
3 6
/ \ \
2 4 7Given key to delete is 3. So we find the node with value 3 and delete it.One valid answer is [5,4,6,2,null,null,7], shown in the following BST. 5
/ \
4 6
/ \
2 7Another valid answer is [5,2,6,null,4,null,7]. 5
/ \
2 6
\ \
4 7
Solution
It’s more easier to understand the flow by using recursion approach. By utilizing the return value, we can easily reduce problem from three cases (key is in left subtree, key is in right subtree and key is on root) to only one case (on root case).
Once we found root contains the key, we should consider following three cases:
- no child: delete root directly
- one child: set root as that child
- two child: find node with minimum value in right subtree, replace root with it and delete that node by recursion.
Complexity
We will traverse up to h
times for finding the target node and finding the node with minimum value in right subtree of the target node if it’s needed, where h
denotes to the length of the longest path from root to leaves in this tree. Therefore, it’s time complexity is O(h). Or you can say O(logn) because h
is bounded by logn
.
For space complexity, because calls of recursion in calling stack will reach h
at most, it uses O(h) (or O(logn)) extra space for this approach.
Follow up
The iteration approach is more complicated but it’s still worth to try it.