Depth of BST Given Insertion Order - Problem
You are given a 0-indexed integer array order of length n, a permutation of integers from 1 to n representing the order of insertion into a binary search tree.
A binary search tree is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
The binary search tree is constructed as follows:
order[0]will be the root of the binary search tree.- All subsequent elements are inserted as the child of any existing node such that the binary search tree properties hold.
Return the depth of the binary search tree. A binary tree's depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Input & Output
Example 1 — Balanced Tree
$
Input:
order = [2,1,4,3]
›
Output:
3
💡 Note:
Insert 2 (root), 1 (left of 2), 4 (right of 2), 3 (left of 4). Longest path: 2→4→3 with depth 3.
Example 2 — Right Skewed Tree
$
Input:
order = [1,2,3,4,5]
›
Output:
5
💡 Note:
Each element goes to the right, creating a linear tree: 1→2→3→4→5 with depth 5.
Example 3 — Single Node
$
Input:
order = [1]
›
Output:
1
💡 Note:
Only one node, so the depth is 1.
Constraints
- 1 ≤ order.length ≤ 1000
- 1 ≤ order[i] ≤ order.length
- All integers in order are unique.
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array representing insertion order: [2,1,4,3]
2
Build BST
Insert elements following BST properties
3
Calculate Depth
Find longest path from root to leaf
Key Takeaway
🎯 Key Insight: BST depth is determined by the insertion sequence - different orders create different tree shapes
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code