Median of a Binary Search Tree Level Problem
Description
LeetCode Problem 3831.
You are given the root of a Binary Search Tree (BST) and an integer level.
The root node is at level 0. Each level represents the distance from the root.
Return the median value of all node values present at the given level. If the level does not exist or contains no nodes, return -1.
The median is defined as the middle element after sorting the values at that level in non-decreasing order. If the number of values at that level is even, return the upper median (the larger of the two middle elements after sorting).
Example 1:

Input: root = [4,null,5,null,7], level = 2
Output: 7
Explanation:
The nodes at level = 2 are [7]. The median value is 7.
Example 2:

Input: root = [6,3,8], level = 1
Output: 8
Explanation:
The nodes at level = 1 are [3, 8]. There are two possible median values, so the larger one 8 is the answer.
Example 3:

Input: root = [2,1], level = 2
Output: -1
Explanation:
There is no node present at level = 2, so the answer is -1.
Constraints:
- The number of nodes in the tree is in the range
[1, 2 * 10^5]. 1 <= Node.val <= 10^60 <= level <= 2 * 10^5
Solution
Approach: Iterative In-order Traversal
The in-order traversal of a binary search tree visits the values in sorted order. So if we walk the tree in order and keep only the nodes whose depth equals level, we get the values of that level already sorted.
We run the in-order traversal with an explicit stack that stores each node together with its depth (the root has depth 0, a child has the parent's depth plus 1). An explicit stack avoids deep recursion, because the tree can have up to 2 * 10^5 nodes in a single chain. Every time we pop a node with depth level, we append its value to a list nums.
If nums is empty, the level does not exist and the answer is -1. Otherwise the answer is nums[len(nums) / 2] (integer division): that is the middle element for an odd count and the upper median for an even count.
Complexity:
- Time:
O(n). - Space:
O(n).
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def levelMedian(self, root: Optional[TreeNode], level: int) -> int:
nums = []
stack = []
node, depth = root, 0
while node or stack:
while node:
stack.append((node, depth))
node, depth = node.left, depth + 1
node, depth = stack.pop()
if depth == level:
nums.append(node.val)
node, depth = node.right, depth + 1
return nums[len(nums) // 2] if nums else -1