
Problem
Solution
Submissions
Recover Binary Search Tree
Certification: Advanced Level
Accuracy: 100%
Submissions: 1
Points: 15
Write a Java program to recover a Binary Search Tree (BST) where exactly two nodes have been swapped incorrectly. You need to restore the tree without changing its structure, only by correcting the swapped nodes. A BST is a binary tree where for each node, all elements in its left subtree are less than the node's value, and all elements in its right subtree are greater than the node's value.
Example 1
- Input: root = [1,3,null,null,2]
- Output: [3,1,null,null,2]
- Explanation:
- Step 1: The BST [1,3,null,null,2] is represented as:
- Step 2: This is not a valid BST because 3 > 1, so the left child should be less than its parent.
- Step 3: We identify that 1 and 3 have been swapped.
- Step 4: After swapping them back, the corrected BST is:
- Step 5: This is now a valid BST.
- Step 1: The BST [1,3,null,null,2] is represented as:
Example 2
- Input: root = [3,1,4,null,null,2]
- Output: [3,1,4,null,null,2]
- Explanation:
- Step 1: The BST [3,1,4,null,null,2] is represented as:
- Step 1: The BST [3,1,4,null,null,2] is represented as:
Constraints
- The number of nodes in the tree is in the range [2, 1000]
- -2^31 ≤ Node.val ≤ 2^31 - 1
- All values in the tree are unique
- Exactly two nodes have been swapped
- Time Complexity: O(n)
- Space Complexity: O(h) where h is the height of the tree (recursion stack)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Perform an in-order traversal of the tree, which should visit nodes in ascending order in a valid BST.
- During traversal, identify the nodes that are out of order.
- There will be either one or two violations where a node is greater than its successor.
- If there's one violation, the two swapped nodes are adjacent in the in-order traversal.
- If there are two violations, the first node of the first violation and the second node of the second violation are the swapped ones.