-
Notifications
You must be signed in to change notification settings - Fork 148
/
KthNode63.java
70 lines (65 loc) · 1.46 KB
/
KthNode63.java
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.so;
import com.so.Common.TreeNode;
import java.util.Stack;
/**
* 第63题
* 给定一棵二叉搜索树,请找出其中的第k小的结点
*
* @author qgl
* @date 2017/08/30
*/
public class KthNode63 {
/**
* 解法一:递归
*
* @param pRoot
* @param k
* @return
*/
private int count = 0;
public TreeNode KthNode(TreeNode pRoot, int k) {
if(pRoot == null) {
return null;
}
TreeNode node = KthNode(pRoot.left, k);
if(node != null) {
return node;
}
count++;
if(count == k) {
return pRoot;
}
node = KthNode(pRoot.right, k);
return node;
}
/**
* 解法二:非递归,借用栈查找
*
* @param pRoot
* @param k
* @return
*/
public TreeNode getKthNode2(TreeNode pRoot, int k) {
if (pRoot == null || k < 1) {
return null;
}
int index = 0;
TreeNode root = pRoot;
Stack<TreeNode> s = new Stack<>();
while (root != null || !s.isEmpty()) {
while (root != null) {
s.push(root);
root = root.left;
}
if (!s.isEmpty()) {
root = s.pop();
index++;
if (index == k) {
return root;
}
root = root.right;
}
}
return null;
}
}