KatInterview

Find the k-th Value in a Level-Order Encoded Tree's Inorder Sequence

Trees & GraphsAuto-graded · 20 test cases
MediumAuto-gradedTrees & Graphsbinary-treeinorder-traversaliterative-traversal

Last updated

Decode a level-order binary tree with null gaps, then return the k-th value in its inorder sequence, or -1 if fewer than k nodes exist.

Find the k-th Value in a Level-Order Encoded Tree's Inorder Sequence

A binary tree is described by a list tree in level order. Each entry is either an integer node value or None (shown as null in samples), meaning there is no node at that position.

Encoding rules

  • tree[0] is the root. If the list is empty or tree[0] is None, the tree is empty.
  • Nodes are processed in the order they were created, starting with the root, using a queue.
  • For each node taken from the queue, the next entry in the list is its left child and the entry after that is its right child. A None entry means that child is absent, and absent children are never placed in the queue.
  • Reading stops once the list is exhausted. Any node left without entries simply has no children (the list may be shorter than a full level and may have no trailing None values).

For example, [3, 1, 4, null, 2] describes: 3 with left child 1 and right child 4; 1 has no left child and has right child 2.

Task

Build the tree and list its values in inorder (left subtree, then node, then right subtree). Return the value at position k (1-indexed) in that sequence.

Return -1 if:

  • the tree is empty,
  • k is less than 1, or
  • the tree has fewer than k nodes.

Otherwise return the value of that node.

Constraints

  • The tree has up to 10^5 nodes, so it may be very deep (like a linked list). Your solution should not depend on deep recursion.
  • Node values are integers.
  • k is an integer; it may exceed the number of nodes, in which case the answer is -1.
  • The input is always a valid level-order encoding as described above.

Examples

Example 1

Input: kth_inorder_value([3, 1, 4, None, 2], 2)

Output: 2

Example 2

Input: kth_inorder_value([5, 3, 6], 4)

Output: -1

Hints

Hint 1

First turn the level-order list into linked nodes using a queue: each dequeued node consumes the next two list entries as its left and right children.

Hint 2

Inorder means left, node, right. You do not need the whole sequence; you can stop as soon as you reach the k-th visited node.

Hint 3

Use an explicit stack instead of recursion: push the whole left chain, pop a node and count it, then move to its right child. If everything is exhausted before the count reaches k, return -1.