|
5 | 5 | import java.util.ArrayList;
|
6 | 6 | import java.util.List;
|
7 | 7 |
|
8 |
| -/** |
9 |
| - * 230. Kth Smallest Element in a BST |
10 |
| - * |
11 |
| - * Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. |
12 |
| -
|
13 |
| - Note: |
14 |
| - You may assume k is always valid, 1 ? k ? BST's total elements. |
15 |
| -
|
16 |
| - Follow up: |
17 |
| - What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine? |
18 |
| -
|
19 |
| - */ |
20 | 8 | public class _230 {
|
21 | 9 |
|
22 | 10 | public static class Solution1 {
|
23 |
| - public int kthSmallest(TreeNode root, int k) { |
24 |
| - List<Integer> inorderList = new ArrayList<>(); |
25 |
| - inorder(root, inorderList); |
26 |
| - return inorderList.get(k - 1); |
27 |
| - } |
28 |
| - |
29 |
| - private void inorder(TreeNode root, List<Integer> inorderList) { |
30 |
| - if (root == null) { |
31 |
| - return; |
32 |
| - } |
33 |
| - if (root.left != null) { |
34 |
| - inorder(root.left, inorderList); |
35 |
| - } |
36 |
| - inorderList.add(root.val); |
37 |
| - if (root.right != null) { |
38 |
| - inorder(root.right, inorderList); |
39 |
| - } |
40 |
| - return; |
41 |
| - } |
42 |
| - } |
43 |
| - |
44 |
| - public static class Solution2 { |
45 | 11 | /**
|
46 | 12 | * Inorder traversal gives the natural ordering of a BST, no need to sort.
|
47 | 13 | */
|
48 |
| - int count = 0; |
49 |
| - int result = Integer.MIN_VALUE; |
50 |
| - |
51 | 14 | public int kthSmallest(TreeNode root, int k) {
|
52 |
| - inorder(root, k); |
53 |
| - return result; |
| 15 | + List<Integer> inorder = new ArrayList(); |
| 16 | + dfs(root, inorder, k); |
| 17 | + return inorder.get(k - 1); |
54 | 18 | }
|
55 | 19 |
|
56 |
| - private void inorder(TreeNode root, int k) { |
| 20 | + private void dfs(TreeNode root, List<Integer> list, int k) { |
57 | 21 | if (root == null) {
|
58 | 22 | return;
|
59 | 23 | }
|
60 |
| - inorder(root.left, k); |
61 |
| - count++; |
62 |
| - if (count == k) { |
63 |
| - result = root.val; |
| 24 | + dfs(root.left, list, k); |
| 25 | + list.add(root.val); |
| 26 | + dfs(root.right, list, k); |
| 27 | + if (list.size() >= (k - 1)) { |
64 | 28 | return;
|
65 | 29 | }
|
66 |
| - inorder(root.right, k); |
67 | 30 | }
|
68 | 31 | }
|
69 | 32 |
|
|
0 commit comments