Find the k-th Value in a Level-Order Encoded Tree's Inorder Sequence
Trees & GraphsAuto-graded · 20 test casesLast 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 ortree[0]isNone, 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
Noneentry 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
Nonevalues).
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,
kis less than 1, or- the tree has fewer than
knodes.
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.
kis 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The work has two stages.
-
Decode the tree. Create the root from
tree[0], then use a queue. Each time a node is dequeued, read the next list entry as its left child and the one after as its right child. Non-Noneentries become new nodes and are enqueued;Noneentries are skipped. This mirrors exactly how the encoding was produced. -
Walk inorder with an explicit stack and stop at k. Push the entire left chain, pop a node (it is the next in inorder order), increase a counter, and return its value when the counter equals
k. Otherwise continue with the popped node's right child. If the loop ends first, the tree has fewer thanknodes, so return-1.
Early exits: an empty list, a None root, or k < 1 return -1 immediately.
Why it is correct
The stack holds the ancestors whose left subtrees are being processed. When a node is popped, its whole left subtree has already been visited, and its right subtree has not. So pops occur in exact inorder order, and the k-th pop is the k-th inorder value. Using an iterative loop avoids recursion limits on very deep (skewed) trees. If the traversal ends before the count reaches k, all nodes have been counted and there are fewer than k, so -1 is correct.
Complexity
- Time: O(n) to build the tree, plus O(h + k) for the traversal, so O(n) overall.
- Space: O(n) for the nodes and queue, plus O(h) for the stack.
Reference solution
from collections import deque
from typing import List, Optional
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def kth_inorder_value(tree: List[Optional[int]], k: int) -> int:
if not tree or tree[0] is None or k <= 0:
return -1
root = TreeNode(tree[0])
queue = deque([root])
index = 1
n = len(tree)
while queue and index < n:
node = queue.popleft()
if index < n and tree[index] is not None:
node.left = TreeNode(tree[index])
queue.append(node.left)
index += 1
if index < n and tree[index] is not None:
node.right = TreeNode(tree[index])
queue.append(node.right)
index += 1
stack = []
node = root
count = 0
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
count += 1
if count == k:
return node.val
node = node.right
return -1