FunctionRacerProblemsRace

Median of a BST

EasyTreesPython, JavaScript, TypeScript, Java, C++

You are given the root of a binary tree. Return the median of the values in the BST. If the number of nodes is odd, it is the middle value in sorted order. If it is even, return the smaller of the two middle values. The tree has at least one node. In a binary search tree every value in a left subtree is smaller than its node and every value in a right subtree is larger.

Trees appear in the tests in level order, with null for a missing child, like [3,9,20,null,null,15,7]. Each node is a TreeNode with .val, .left and .right; the class is already defined for you.

Example 1

root [4,2,6,1,3]
returns 3

Sorted: 1, 2, 3, 4, 6. The middle is 3.

Example 2

root [2,1,3,null,null,null,4]
returns 2

Sorted: 1, 2, 3, 4. Two middles 2 and 3: return 2.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Trees problems