Median of a BST
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
Sorted: 1, 2, 3, 4, 6. The middle is 3.
Example 2
Sorted: 1, 2, 3, 4. Two middles 2 and 3: return 2.
Constraints
1 <= number of nodes <= 100-1000 <= node.val <= 1000- The tree is a valid BST with distinct values.
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.