|
| 1 | +/** |
| 2 | + * Given a binary search tree, write a function kthSmallest to find the kth |
| 3 | + * smallest element in it. |
| 4 | + * |
| 5 | + * Note: |
| 6 | + * You may assume k is always valid, 1 ≤ k ≤ BST's total elements. |
| 7 | + * |
| 8 | + * Follow up: |
| 9 | + * What if the BST is modified (insert/delete operations) often and you need to |
| 10 | + * find the kth smallest frequently? How would you optimize the kthSmallest |
| 11 | + * routine? |
| 12 | + * |
| 13 | + */ |
| 14 | + |
| 15 | +/** |
| 16 | + * Definition for a binary tree node. |
| 17 | + * public class TreeNode { |
| 18 | + * int val; |
| 19 | + * TreeNode left; |
| 20 | + * TreeNode right; |
| 21 | + * TreeNode(int x) { val = x; } |
| 22 | + * } |
| 23 | + */ |
| 24 | + |
| 25 | + |
| 26 | +public class KthSmallestElementInABST230 { |
| 27 | + public int kthSmallest(TreeNode root, int k) { |
| 28 | + Stack<Integer> st = new Stack<>(); |
| 29 | + kthSmallest(root, k, st); |
| 30 | + return st.pop(); |
| 31 | + } |
| 32 | + |
| 33 | + public void kthSmallest(TreeNode root, int k, Stack<Integer> st) { |
| 34 | + if (root == null) return; |
| 35 | + |
| 36 | + kthSmallest(root.left, k, st); |
| 37 | + if (st.size() == k) return; |
| 38 | + |
| 39 | + st.push(root.val); |
| 40 | + if (st.size() == k) return; |
| 41 | + |
| 42 | + kthSmallest(root.right, k, st); |
| 43 | + } |
| 44 | + |
| 45 | + |
| 46 | + public int kthSmallest2(TreeNode root, int k) { |
| 47 | + int[] i = new int[]{0, 0}; |
| 48 | + kthSmallest(root, k, i); |
| 49 | + return i[1]; |
| 50 | + } |
| 51 | + |
| 52 | + public void kthSmallest(TreeNode root, int k, int[] i) { |
| 53 | + if (root.left != null) kthSmallest(root.left, k, i); |
| 54 | + if (i[0] == k) return ; |
| 55 | + |
| 56 | + i[0] = i[0] + 1; |
| 57 | + i[1] = root.val; |
| 58 | + if (i[0] == k) return; |
| 59 | + |
| 60 | + if (root.right != null) kthSmallest(root.right, k, i); |
| 61 | + } |
| 62 | + |
| 63 | +} |
0 commit comments