Depth of BST Given Insertion Order - Problem
You're given a sequence of integers representing the insertion order into a Binary Search Tree (BST). Your task is to determine the maximum depth of the BST that would be constructed following these insertions.
๐ณ BST Properties:
- Left subtree contains only nodes with values less than the parent
- Right subtree contains only nodes with values greater than the parent
- Both subtrees are also valid BSTs
Construction Process: The first element becomes the root, and each subsequent element is inserted following BST rules - compare with existing nodes and go left if smaller, right if larger, until finding an empty spot.
Goal: Return the depth (number of nodes along the longest path from root to leaf) of the resulting BST.
Example: For insertion order [2,1,3], we get a balanced tree with depth 2. For [1,2,3], we get a right-skewed tree with depth 3.
Input & Output
example_1.py โ Balanced Tree
$
Input:
order = [2, 1, 3]
โบ
Output:
2
๐ก Note:
The BST formed is balanced: root=2, left child=1, right child=3. The maximum depth is 2 (root to any leaf).
example_2.py โ Right Skewed Tree
$
Input:
order = [1, 2, 3, 4]
โบ
Output:
4
๐ก Note:
Each element is greater than the previous, creating a right-skewed tree: 1โ2โ3โ4. Maximum depth is 4.
example_3.py โ Complex Tree
$
Input:
order = [2, 1, 4, 3]
โบ
Output:
3
๐ก Note:
Tree structure: root=2, left=1, right=4, and 3 becomes left child of 4. Longest path is 2โ4โ3 with depth 3.
Constraints
- 1 โค order.length โค 105
- 1 โค order[i] โค 105
- order is a permutation of integers from 1 to n
- All values in order are unique
Visualization
Tap to expand
Understanding the Visualization
1
CEO Takes Position
First person becomes CEO (root) at level 1
2
Employees Find Positions
Each new employee compares their ID with existing employees to find their reporting position
3
Track Organization Depth
Keep track of the deepest management level as the hierarchy grows
Key Takeaway
๐ฏ Key Insight: BST depth calculation is like measuring organizational hierarchy depth - we can track the maximum management level without building the complete org chart!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code