Skip to main content
Back to problems
#1902
Medium Algorithms

Depth of bst given insertion order

Array Tree Binary Search Tree Binary Tree Ordered Set
42.5% acceptance
Mar 31, 2026
111
12
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.

Solution

Rust
Time O(n log n)
Space O(n)
LeetCode
solution.rs
use std::collections::BTreeMap;

impl Solution {
  pub fn max_depth_bst(order: Vec<i32>) -> i32 {
    let mut map: BTreeMap<i32, i32> = BTreeMap::new();
    let mut max_depth = 0;
    for val in order {
      let left_depth = map.range(..val).next_back().map_or(0, |(_, &d)| d);
      let right_depth = map.range(val..).next().map_or(0, |(_, &d)| d);
      let depth = left_depth.max(right_depth) + 1;
      map.insert(val, depth);
      max_depth = max_depth.max(depth);
    }
    max_depth
  }
}