Delete Node in a BST
Updated
Problem statement
You are given the root of a binary search tree and an integer key. Delete the node whose value equals key, if it exists, and return the updated root.
The returned tree must remain a binary search tree. When the deleted node has two children, replace its value with the smallest value in its right subtree, then delete that successor node. Using this rule means there is only one correct output tree.
Function
deleteNode(root: TreeNode, key: int) → TreeNodeExamples
Example 1
root = [5,3,6,2,4,null,7]key = 3return = [5,4,6,2,null,null,7]Removed
Moved or new
Node 3 has two children. Its inorder successor is 4, which takes its place.
Example 2
root = [5,3,6,2,4,null,7]key = 0return = [5,3,6,2,4,null,7]The key is absent, so the tree is unchanged.
Example 3
root = []key = 0return = []An empty tree remains empty.
Constraints
- The tree contains between
0and10000nodes. -100000 <= Node.val <= 100000.- Every node value is unique and the input is a valid binary search tree.
-100000 <= key <= 100000.
More Tokopedia interview questions
- Interleaving StringPHONE SCREEN · Seen Jul 2021
- Rotate ImagePHONE SCREEN · Seen Jul 2021
- Validate Binary Search TreeONSITE INTERVIEW · Seen Aug 2021
- Kth Largest Element in an ArrayONSITE INTERVIEW · Seen Jul 2021
- Online Stock SpanONSITE INTERVIEW · Seen Jul 2021
- Vertical Order Traversal of a Binary TreeONSITE INTERVIEW · Seen Jul 2021
Similar questions at other companies
- AVL Insertion and RotationsSquarepoint Capital · PHONE SCREEN
- Delete Node in a BSTBloomberg LP · PHONE SCREEN · ONSITE INTERVIEW
- Convert a Sorted Linked List to a Balanced BSTMeta · PHONE SCREEN
- Binary Tree Target-Sum PathsByteDance · PHONE SCREEN
- Top K Pins with Insert and QueryPinterest · PHONE SCREEN
- Construct a Binary Tree from Preorder and InordereBay · PHONE SCREEN
- Filter Data with Composable PredicatesCoreWeave · PHONE SCREEN
- Trim a Binary Search Tree to a RangeGoogle · PHONE SCREEN
- Count Uni-Valued SubtreesAmazon · PHONE SCREEN
- Reconstruct a BST from PreorderLyft · PHONE SCREEN