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
Corporate Hierarchy = BST StructureInsertion Order: [5, 3, 7, 2, 4, 6, 8]5CEO (Level 1)3VP Left7VP Right2Manager4Manager6Manager8ManagerOrganization Depth: 3 Levelsโœ“ Balanced hierarchy with efficient reporting structureEach level represents the depth in our BST
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!
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
42.4K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen