Python 0099.py
class Solution:
def recoverTree(self, root: Optional[TreeNode]) -> None:
# in-order traversal must be non-decreasing
inorder = []
def deeper(node):
if node:
deeper(node.left)
inorder.append(node)
deeper(node.right)
deeper(root)
# two elements are out of sync
s = sorted([ x.val for x in inorder ])
a = 0
while inorder[a].val == s[a]:
a += 1
b = len(s) - 1
while inorder[b].val == s[b]:
b -= 1
# swap
inorder[a].val, inorder[b].val = inorder[b].val, inorder[a].val
Difficulty
and has an acceptance rate of about 60% (1+ million submissions).
Typical patterns to solve this problem:
- Binary Search Tree
- Binary Tree
- Depth First Search
- Tree
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The implementation restores a binary search tree (BST) in which exactly two node values have been swapped. It relies on the property that an in-order traversal of a correct BST yields a non-decreasing sequence of values. By collecting the nodes in in-order, sorting the extracted values, locating the two positions where the original order diverges from the sorted order, and finally swapping the values of the offending nodes, the tree is repaired in place.
In-order Collection
The first phase performs a depth-first in-order walk, appending each visited node to a list. The nested helper deeper recurses left, records the current node, then recurses right.
inorder = []
def deeper(node):
if node:
deeper(node.left)
inorder.append(node)
deeper(node.right)
deeper(root)
At the end of this step inorder holds references to all tree nodes in the order they appear during an in-order traversal.
Sorted Reference Values
A separate list containing only the node values is built and sorted. This sorted list represents the correct ordering of values for a valid BST.
s = sorted([x.val for x in inorder])
Because the original list inorder preserves the structural order, the sorted list s serves as a reference against which discrepancies can be detected.
Detecting the Swapped Positions
Two indices, a and b, are advanced from opposite ends of the lists until a mismatch is found. The left-most mismatch index a points to the first node whose value is out of place, while the right-most mismatch index b points to the second.
a = 0
while inorder[a].val == s[a]:
a += 1
b = len(s) - 1
while inorder[b].val == s[b]:
b -= 1
If the swapped nodes are adjacent in the in-order sequence, a and b will become consecutive indices; the loops still isolate the two incorrect positions correctly.
Restoring the Tree
The final step swaps the values of the two identified nodes directly, leaving the tree topology untouched.
inorder[a].val, inorder[b].val = inorder[b].val, inorder[a].val
By modifying only the val fields, the algorithm avoids any restructuring of pointers or reconstruction of subtrees.
Edge Cases Handled
When the two swapped nodes are far apart in the in-order sequence, the mismatched indices are separated by many positions; the scanning loops still locate the outermost mismatches, ensuring the correct pair is swapped.
If the swapped nodes happen to be neighbors in the in-order traversal, the first loop stops at the first out-of-order element and the second loop stops at the next element, resulting in adjacent indices a and b. The swap operation correctly restores order in this scenario.
The routine also works for the minimal non-trivial tree consisting of exactly two nodes. The in-order collection yields both nodes, the sorted list reverses their values, and the mismatch detection identifies the two positions, leading to a single swap that restores the BST property.
Performance Optimizations
The algorithm performs a single recursive traversal to gather node references, which is efficient in terms of call overhead because each node is visited exactly once.
Storing direct references to the original node objects (inorder.append(node)) enables an in-place value swap without allocating additional node structures or rebuilding the tree. This reduces memory churn and keeps the modification localized to the two affected nodes.
The mismatch detection uses two linear scans from opposite ends, terminating as soon as the first discrepancy is found on each side. This early-exit behavior avoids unnecessary comparisons once the swapped positions are identified.
Overall, the approach balances simplicity with practical efficiency by limiting the number of traversals and by mutating only the necessary fields.
ELI5 - Simplified Explanation
Imagine you have a line of building blocks that should all be in order from smallest to biggest. Sometimes, two of the blocks accidentally switch places, and the line looks a bit messy.
First, the code walks through every block one by one from left to right, like a little train picking up each block in the order they are currently standing. It puts these blocks into a list so it can look at them all at once.
Next, it creates a secret checklist of what the blocks ought to look like if they were lined up perfectly from smallest to biggest. Now it can compare the messy line to the perfect checklist.
It starts at the very beginning of the line to find the first block that is standing in the wrong spot. Then it starts at the very end of the line and works backward to find the second block that is out of place.
Once it finds both of those silly blocks, it simply swaps them back into their correct spots. Now everything is back in the right order just like it should be.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | JS | C# | Go | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | aylei | Rust | |||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| Garvit244 | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| wisdompeak | C++ | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| aylei | Rust | ||||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| Garvit244 | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| wisdompeak | C++ | ||||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 144: Binary Tree Preorder Traversal
- problem 145: Binary Tree Postorder Traversal
- problem 222: Count Complete Tree Nodes
- problem 404: Sum of Left Leaves
- problem 501: Find Mode in Binary Search Tree
- problem 543: Diameter of Binary Tree
- problem 559: Maximum Depth of N-ary Tree
- problem 589: N-ary Tree Preorder Traversal
- problem 590: N-ary Tree Postorder Traversal
- problem 637: Average of Levels in Binary Tree
- problem 700: Search in a Binary Search Tree
- problem 703: Kth Largest Element in a Stream
- problem 79: Word Search
- problem 81: Search in Rotated Sorted Array II
- problem 97: Interleaving String
- problem 173: Binary Search Tree Iterator
- problem 199: Binary Tree Right Side View
- problem 230: Kth Smallest Element in a BST
- problem 235: Lowest Common Ancestor of a Binary Search Tree
- problem 341: Flatten Nested List Iterator
- problem 429: N-ary Tree Level Order Traversal
- problem 508: Most Frequent Subtree Sum
- problem 513: Find Bottom Left Tree Value
- problem 538: Convert BST to Greater Tree
- problem 65: Valid Number
- problem 85: Maximal Rectangle
- problem 87: Scramble String
- problem 126: Word Ladder II
- problem 127: Word Ladder
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality