Ctrl K

Search Tree Height From Insertion Order

Medium
The numbers 1 to n are inserted one by one into an initially empty binary search tree, in the order given by keys. The first number becomes the root; each next one walks down from the root, going left when it is smaller than the current node and right when it is larger, and becomes a new leaf in the first empty spot. Return the height of the resulting tree: the number of nodes on the longest path from the root to a leaf. Simulating the insertions directly can take O(n²) when the tree degenerates into a chain. Try to do better.
Example 1
keys=[3, 1, 2, 5, 4] → 3

The root is 3; 1 goes left, 2 becomes the right child of 1; 5 is the right child of 3 and 4 the left child of 5. The longest paths, 3 → 1 → 2 and 3 → 5 → 4, have 3 nodes each.

Example 2
keys=[1, 2, 3] → 3

The keys arrive in increasing order, so the tree becomes a chain going right, of height 3.

Example 3
keys=[4, 2, 6, 1, 3, 5, 7] → 3

This gives a perfectly balanced tree with three levels.

Constraints
  • 1 ≤ n ≤ 10⁵
  • keys is a permutation of the numbers from 1 to n
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPreorder of a Search Tree MediumSearch Tree From a Visit Log MediumFloor and Ceiling in a Search Tree MediumBalanced Tree from a Sorted List EasyOther Orders for the Same Search Tree Hard
loading Python…
Input
keys=[3, 1, 2, 5, 4]
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 109 tests on the server, hidden ones included.