-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKth Smallest Element in a BST.java
More file actions
40 lines (36 loc) · 1.09 KB
/
Kth Smallest Element in a BST.java
File metadata and controls
40 lines (36 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
// actually it is an inorder traversal
public class Solution {
public int kthSmallest(TreeNode root, int k) {
if(root == null) return 0;
Stack<TreeNode> stack = new Stack<TreeNode>();
int count = 0;
TreeNode node = root;
while(!stack.isEmpty() || node != null){
while(node != null){
stack.push(node);
node = node.left;
}
TreeNode top = stack.pop();
if(--k == 0){
return top.val;
}
node = node.right;
}
}
// follow up: change the structure of the treenode
/*
添加一个属性,去记录left child的值。
当前节点设置为node
如果K = leftchildCt + 1,证明root就是要找的值;
如果K > leftchildCt + 1,说明在右子树, K = K - (leftchildCt + 1), node = node. right;
最后的情况就是在左子树,node = node.left;
*/