Return the value at a requested ascending rank in a binary search tree.
Problem
Input. The root of a finite strict binary search tree and a one-based integer rank k.
Output. Return the kth smallest stored value, not the node object or its depth.
Rules. Every left descendant is smaller than its ancestor; every right descendant is larger.
Values are distinct, and there are no cycles or shared children.
Require 1 <= k <= the node count. Leave all nodes and links unchanged.
Example. A tree with root 3, left child 1, right child 4, and 1.right = 2 has values [1, 2, 3, 4].
For k = 2, return 2.
Picture
For rank four, push 5,3,2,1 down the left spine. Four pushes do not mean four values have been emitted.
| Action | Deferred ancestors after action | Rank still needed |
|---|---|---|
| Push through 1 | 5,3,2,1, top 1 | 4 |
| Pop 1 | 5,3,2 | 3 |
| Pop 2 | 5,3 | 2 |
| Pop 3; enter its right child | 5 | 1 |
| Push and pop 4 | 5 | 0: return 4 |
Problem trace
Separate three-node tree: rank belongs to emissions, not pushes
Reference drawing
Problem trace
Count a node when inorder visits it, not when it enters the stack
Execution trace
Original coordinate inventory
- root
- (0, 3)
- input
- tree=[5,3,7,2,4,6,8,1], k=4
- cursor
- root=5
Original coordinate inventory
- root
- (0, 3)→(2, 1)
- cursor
- root=5→root=3
- stack
- []→[5]
Original coordinate inventory
- root
- (2, 1)→(4, 0)
- cursor
- root=3→root=2
- stack
- [5]→[5,3]
Original coordinate inventory
- root
- (4, 0)→(6, 0)
- cursor
- root=2→root=1
- stack
- [5,3]→[5,3,2]
Original coordinate inventory
- cursor
- root=1→root=null after 1
- stack
- [5,3,2]→[5,3,2,1] top=1
Original coordinate inventory
- cursor
- root=null after 1→visit 1
- stack
- [5,3,2,1] top=1→[5,3,2]
- arithmetic
- not shown→4 - 1 = 3
Original coordinate inventory
- visit 2
- (6, 0)→(4, 0)
- cursor
- visit 1→visit 2
- stack
- [5,3,2]→[5,3]
Original coordinate inventory
- root
- (4, 0)→(4, 2)
- cursor
- visit 2→root=4
- stack
- [5,3]→[5]
Original coordinate inventory
- cursor
- root=4→root=null after 4
- stack
- [5]→[5,4] top=4
- remaining
- not shown→1
Original coordinate inventory
- cursor
- root=null after 4→return 4
- stack
- [5,4] top=4→[5]
- arithmetic
- not shown→1 - 1 = 0
- Recognize it
- The input is a BST and the question asks for an order statistic, so inorder traversal produces the required sorted rank without sorting all values.
- Keep true
- Before each pop, the stack top is the smallest unvisited node reachable from the processed search frontier; completed pops are in strictly ascending BST order.
- Reuse it
- Use inorder as a sorted stream for BST rank, range, predecessor, and successor tasks, and stop as soon as the requested portion of that stream is consumed.
Code
Use this node type for a local run.
from dataclasses import dataclass
@dataclass
class TreeNode:
val: int
left: "TreeNode | None" = None
right: "TreeNode | None" = None
def kth_smallest(root: TreeNode | None, k: int) -> int:
stack: list[TreeNode] = []
while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
k -= 1
if k == 0:
return root.val
root = root.right
raise ValueError("k is larger than the tree")
Count Only Emitted Nodes
All left-subtree values precede a node; all right-subtree values follow it. That BST contract makes inorder a sorted stream.
After pushing a complete left spine, the stack top is the smallest unvisited node.
Pop it, decrement k, then either return or continue from its right child. The stack retains ancestors still awaiting emission.
In the example, returning four leaves root five and its entire right subtree unvisited.
For valid rank k, time is and space for height .
Even rank one may require a full-height descent. A BST is not necessarily balanced, so logarithmic height is not guaranteed.
The source expects a positive rank. Nonpositive or oversized ranks exhaust traversal and raise its same size error; an empty tree does too.
The platform supplies TreeNode with val, left, and right; this snippet assumes that definition.
Recall: Why not decrement on push? The fourth pushed node is one, but the fourth emitted value is four.
Rank from the Largest End
Choose this when: Rank orientation changes, but the strict BST contract stays the same.
Visit right, node, left. Decrement only on pop, as before.
def kth_largest_bst(root, rank):
if rank <= 0:
raise ValueError("positive rank required")
stack = []
while root or stack:
while root:
stack.append(root)
root = root.right
root = stack.pop()
rank -= 1
if rank == 0:
return root.val
root = root.left
raise ValueError("rank exceeds size")
The second largest value in the pictured tree is seven. Reversing a comparison alone cannot reverse traversal order.
Time remains for valid ranks; stack space remains . No tree links change.
Precompute Counts for Repeated Queries
Choose this when: Many rank requests share an unchanged tree.
Count each subtree once. Its left size tells whether to descend left, emit the current node, or skip that whole prefix.
def bst_rank_queries(root, ranks):
sizes = {}
def measure(node):
if node is None:
return 0
size = 1 + measure(node.left) + measure(node.right)
sizes[id(node)] = size
return size
total = measure(root)
result = []
for rank in ranks:
if not 1 <= rank <= total:
result.append(None)
continue
node = root
while node is not None:
left_size = sizes.get(id(node.left), 0)
if rank == left_size + 1:
result.append(node.val)
break
if rank <= left_size:
node = node.left
else:
rank -= left_size + 1
node = node.right
return result
Keys use object identity, not value or structural equality. Nodes need not be hashable.
Ranks 1,4,8,0 return [1,4,8,None]; invalid integer ranks return None rather than raising.
Preprocessing takes time and count storage; each query takes time. The returned list also stores one result per query.
This preprocessing is recursive, so deep trees can exceed Python’s recursion limit. Rebuild counts after mutations; balancing is a separate requirement.