Skip to content

Commit cb67f48

Browse files
authored
Merge pull request neetcode-gh#160 from r1cky0/patch-6
Create 230-Kth-Smallest-Element-in-a-BST.java
2 parents 999b33c + 41844e6 commit cb67f48

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
14+
* }
15+
*/
16+
class Solution {
17+
public int kthSmallest(TreeNode root, int k) {
18+
List<Integer> list = new ArrayList<>();
19+
inorder(root, list);
20+
return list.get(k - 1);
21+
}
22+
23+
private void inorder(TreeNode root, List<Integer> list) {
24+
if (root == null) return;
25+
26+
inorder(root.left, list);
27+
list.add(root.val);
28+
inorder(root.right, list);
29+
}
30+
}

0 commit comments

Comments
 (0)