Skip to content
RED SAGSkills

Kth Smallest Badge Number

A binary tree is given as a level-order array: tree[0] is the root, then the children of each real node are listed left to right, level by level. A missing child is written as null, and the children of a missing node are not listed at all. For example [1,2,3,null,4] is root 1 with children 2 and 3, where 2 has only a right child 4.

Employee badge numbers are stored in a binary search tree (left subtree smaller, right subtree larger, all distinct). Return the k-th smallest badge number, counting from 1.

An in-order walk visits the values in sorted order; stop as soon as you reach the k-th one.

Example 1

Input: tree = [3,1,4,null,2], k = 1
Output: 1
Explanation: Sorted order is 1, 2, 3, 4.

Example 2

Input: tree = [5,3,6,2,4,null,null,1], k = 3
Output: 3
Explanation: Sorted order is 1, 2, 3, 4, 5, 6.

Constraints

  • 1 <= k <= number of nodes <= 10^4
  • 1 <= node value <= 10^6
Hint 1

In-order traversal (left, node, right) of a BST yields sorted values.

Hint 2

Use an explicit stack so you can stop after k steps.

Good practice for: Backend Developer, Full Stack Developer, Database Administrator, Data Engineer, Cloud Engineer

Run checks your code on 3 sample tests. Submit runs all 8 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.