Skip to problem
←

Median of a Binary Search Tree

Hard 0 attempts

You're given the root of a binary search tree. Find the median value among all the node values — if the tree holds an even number of nodes, the median is the average of the two values in the middle when sorted.

Function contract

root is a nonempty binary search tree. Test inputs use level-order arrays with null for missing children; the function receives nodes with val, left, and right properties.

Output: Return the middle sorted value for an odd node count, or the arithmetic mean of the two middle sorted values for an even count.

Example 1

Input
root = [6,3,8,1,4,7,9]
Output
6

Example 2

Input
root = [2,1]
Output
1.5
Constraints
  • 1 <= N <= 10^4
  • Node values are integers in [-10^9, 10^9].
  • The input satisfies the binary search tree ordering property.

Iterative Inorder

Collect the sorted node values with an explicit stack. Return the middle value for an odd count or the average of the two middle values for an even count.

javascript
function findMedian(root) {
  const stack = [],
    values = [];
  let current = root;
  while (current || stack.length) {
    while (current) {
      stack.push(current);
      current = current.left;
    }
    current = stack.pop();
    values.push(current.val);
    current = current.right;
  }
  const mid = Math.floor(values.length / 2);
  return values.length % 2 ? values[mid] : (values[mid - 1] + values[mid]) / 2;
}

Time: O(n) | Space: O(n) auxiliary space, excluding output

Loading discussion…

Saved in this browser only. Private to you.

JavaScript