Skip to content

Commit 8211538

Browse files
committed
add k smallest in bst
1 parent c434331 commit 8211538

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed

kth-smallest-element-in-a-bst/README.md

Whitespace-only changes.
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode(int x) { val = x; }
8+
* }
9+
*/
10+
public class Solution {
11+
12+
boolean reachLeftMost = false;
13+
boolean stop = false;
14+
15+
int kth = 0;
16+
int k = 0;
17+
18+
void search(TreeNode root) {
19+
20+
if(stop){
21+
return;
22+
}
23+
24+
// visit
25+
if(root == null){
26+
reachLeftMost = true;
27+
return;
28+
}
29+
30+
search(root.left);
31+
32+
if(reachLeftMost) {
33+
k--;
34+
}
35+
36+
if(k == 0){
37+
kth = root.val;
38+
stop = true;
39+
return;
40+
}
41+
42+
search(root.right);
43+
}
44+
45+
public int kthSmallest(TreeNode root, int k) {
46+
this.k = k;
47+
search(root);
48+
49+
return kth;
50+
}
51+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
layout: solution
3+
title: Kth Smallest Element in a BST
4+
date: 2015-07-02 14:16:21+08:00
5+
leetcode_id: 230
6+
---
7+
{% include_relative README.md %}

0 commit comments

Comments
 (0)