Problem 99

Abstract / Summary

Fix two swapped nodes in a binary search tree so it becomes valid again.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
25 lines | 678 bytes | submitted September 1, 2023 | GitHub   17% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 6.19 | σ = 1.49

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
50 links | 35 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Recover Binary Search Tree (with Follow Up) | Live Coding with Explanation | Leetcode #99'
Algorithms Made Easy 17 mins
Recover Binary Search Tree (with Follow Up) | Live Coding with Explanation | Leetcode #99
YouTube video 'Recover Binary Search Tree | Using Morris Traversal With O(1) Space | Leetcode 99 Solution'
Pepcoding 33 mins
Recover Binary Search Tree | Using Morris Traversal With O(1) Space | Leetcode 99 Solution
YouTube video 'Recover Binary Search Tree | LeetCode 99 | Programming Tutorials'
Programming Tutorials 16 mins
Recover Binary Search Tree | LeetCode 99 | Programming Tutorials
YouTube video 'Recover Binary Search Tree | Leetcode 99 | BST | Day-19'
Ayushi Sharma 16 mins
Recover Binary Search Tree | Leetcode 99 | BST | Day-19
YouTube video 'Recover Binary Search Tree | Leet code 99 | Theory explained + Python code'
Sai Anish Malla 26 mins
Recover Binary Search Tree | Leet code 99 | Theory explained + Python code
YouTube video 'Recover Binary Search Tree | Leetcode 99 | Binary Search Tree 🔥🔥 | Live coding session'
Coding Decoded 8 mins
Recover Binary Search Tree | Leetcode 99 | Binary Search Tree 🔥🔥 | Live coding session
YouTube video 'LeetCode 99. Recover Binary Search Tree'
Happy Coding 49 mins
LeetCode 99. Recover Binary Search Tree
YouTube video 'Daily Leetcode #749: Apr 19, 2022 - 99. Recover Binary Search Tree'
Programming Live with Larry 19 mins
Daily Leetcode #749: Apr 19, 2022 - 99. Recover Binary Search Tree
YouTube video 'Recover Binary Search Tree -- LeetCode - 99 -- 3 Ways'
codewynk 28 mins
Recover Binary Search Tree -- LeetCode - 99 -- 3 Ways
YouTube video 'LeetCode 99. [HARD] Recover Binary Search Tree'
Francesco Manicardi 9 mins
LeetCode 99. [HARD] Recover Binary Search Tree
YouTube video 'Daily Leetcode #214: Oct 31, 2020 - 99. Recover Binary Search Tree'
Programming Live with Larry 19 mins
Daily Leetcode #214: Oct 31, 2020 - 99. Recover Binary Search Tree
YouTube video 'LeetCode 99 | Recover Binary Search Tree | InOrder | Java'
Sleepy Cracker 7 mins
LeetCode 99 | Recover Binary Search Tree | InOrder | Java
YouTube video 'Leetcode [099] Recover Binary Search Tree'
SDE Skills 21 mins
Leetcode [099] Recover Binary Search Tree
YouTube video 'Leetcode Question 99 "Recover Binary Search Tree" in Javascript'
Ghumman Tech 5 mins
Leetcode Question 99 "Recover Binary Search Tree" in Javascript
YouTube video 'Leetcode 99: Recover Binary Search Tree'
Algorithms Casts 27 mins
Leetcode 99: Recover Binary Search Tree
YouTube video '99. Recover Binary Search Tree (LeetCode)'
hakunamatasq 8 mins
99. Recover Binary Search Tree (LeetCode)
YouTube video 'Recover Binary Search Tree (LeetCode 99) - Solution Explained'
CodeLucky 4 mins
Recover Binary Search Tree (LeetCode 99) - Solution Explained
YouTube video 'No Sound Leetcode 99: Recover Binary Search Tree'
ExtremeProgrammer 5 mins
No Sound Leetcode 99: Recover Binary Search Tree
YouTube video 'Day 356: LeetCode Problem 99. Recover Binary Search Tree - Swift'
iOSxBank 14 mins
Day 356: LeetCode Problem 99. Recover Binary Search Tree - Swift
19 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

30 solutions   September 1, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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