Bird
Raised Fist0
Interview Prepbinary-search-treesmediumAmazonFacebookGoogleMicrosoft

Validate Binary Search Tree

Choose your preparation mode3 modes available
Steps
setup

Initialize previous value to negative infinity

We start by setting prev to negative infinity to ensure the first node's value will be greater.

💡 This initialization is crucial because it sets a baseline for comparison during traversal.
Line:prev = [float('-inf')]
💡 The algorithm uses prev to track the last visited node's value in inorder sequence.
📊
Validate Binary Search Tree - Watch the Algorithm Execute, Step by Step
Watching the algorithm step through each node in order reveals how the BST property is checked incrementally, making it easier to understand than just reading code.
Step 1/13
·Active fillAnswer cell
213
Current node: 1
213
DFS Stack
1 (entered)
Current node: 2
213
DFS Stack
2 (entered)1 (left_done)
Current node: 2
213
DFS Stack
2 (entered)prev=11 (left_done)prev=1
Current node: 2
213
DFS Stack
2 (right_done)prev=11 (left_done)prev=1
Return: true
Current node: 1
213
DFS Stack
1 (left_done)prev=1
Current node: 1
213
DFS Stack
1 (left_done)prev=2
Current node: 3
213
DFS Stack
3 (entered)prev=21 (right_done)prev=2
Current node: 3
213
DFS Stack
3 (left_done)prev=21 (right_done)prev=2
Return: true
Current node: 3
213
DFS Stack
3 (entered)prev=31 (right_done)prev=3
Current node: 3
213
DFS Stack
3 (right_done)prev=31 (right_done)prev=3
Return: true
Current node: 1
213
DFS Stack
1 (returning)prev=3
Return: true
213
Return: true

Key Takeaways

Inorder traversal of a BST produces a strictly increasing sequence of node values.

This insight is hard to see from code alone but becomes obvious when watching the traversal order and comparisons.

Tracking the previous node's value during traversal allows efficient validation without extra space.

The visualization shows how a single variable 'prev' is updated and used to check BST property incrementally.

The recursion call stack reflects the traversal path and helps understand how the algorithm backtracks after leaf nodes.

Seeing the call stack states clarifies the recursion flow and why the algorithm returns early on violations.