1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Solution { public int kthSmallest(TreeNode root, int k) {
Stack<TreeNode> stack = new Stack<>(); while (!stack.isEmpty() || root != null) { while (root != null) { stack.push(root); root = root.left; }
TreeNode node = stack.pop(); if (--k == 0) { return node.val; } root = node.right; }
throw new RuntimeException("Cannot find kth smallest node"); } }
|
References
230. Kth Smallest Element in a BST