804. Median of a Binary Search Tree Level

You are given the root of a Binary Search Tree (BST) along with an integer level. The root node is located at level 0. Every level reflects the distance from the root.

Return the median value of all node values at the specified level. If the level does not exist or there are no nodes, return -1.

The median is determined by sorting the values at that level in non-decreasing order. If the number of values at that level is equal, return the higher median (the greater of the two middle components after sorting).

Note:

  • -1 in Input array represents the empty/null node.

Example 1:

Input:Ā root = [4, -1, 5, -1, 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.

Now Your Turn!

Pick the correct output for the given input

Input:Ā root = [2, 1], level = 2

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • The number of nodes in the tree is in the rangeĀ [1, 2 * 105]
  • 1 <= Node.val <= 106
  • 0 <= level <= 2 * 10​​​​​​​5

Hints

Frequently Occurring Doubts

0
/*
Defination of TreeNode
class TreeNode {
public:
int data;
TreeNode *left;
TreeNode *right;
TreeNode() : data(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : data(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : data(x), left(left), right(right) {}
};
*/
Ā 
class Solution {
public:
int levelMedian(TreeNode* root, int level) {
// Your code goes here
}
};
Test Case

Input:

Level
Root