Pattern visualizer
Kth Largest Element in a BST
Reverse inorder (right, node, left) is the mirror image of the standard traversal: instead of ascending order it visits every key in strictly descending order. So the kth largest element is simply the kth value that traversal emits, and there is no need to collect all n values first: an explicit stack can walk right as far as possible, pop one node at a time, count down k, and return the instant k reaches zero — skipping every node past the answer. Animated on: root = [5,3,6,2,4,null,null,1], k = 3 — return the kth largest value in the BST (1-indexed). Expected: 4..
Early-stopping reverse-inorder traversal with an explicit stack
Call stack
Call kthLargest(root, k=3). Point node at the root, 5, with an empty stack. A BST's REVERSE inorder traversal (right, node, left) visits keys in strictly descending order, so the kth key it emits is the kth largest — no sorting needed.
1node <- root2stack <- EMPTY3WHILE node != null OR stack NOT EMPTY:4 WHILE node != null:5 PUSH node TO stack6 node <- node.right7 node <- POP(stack)8 k <- k - 19 IF k = 0:10 RETURN node.val11 node <- node.left
← / → step · space play · Home restart