forked from carpeventus/coding-interviews
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKthNode.java
More file actions
37 lines (32 loc) · 906 Bytes
/
KthNode.java
File metadata and controls
37 lines (32 loc) · 906 Bytes
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
package Chap6;
import java.util.LinkedList;
/**
* 给定一颗二叉搜索树,请找出排名第k的结点。
*/
public class KthNode {
private class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public TreeNode findKthNode(TreeNode pRoot, int k) {
if (pRoot == null || k <= 0) return null;
LinkedList<TreeNode> stack = new LinkedList<>();
int count = 0;
while (pRoot != null || !stack.isEmpty()) {
while (pRoot != null) {
stack.push(pRoot);
pRoot = pRoot.left;
}
if (!stack.isEmpty()) {
pRoot = stack.pop();
if (++count == k) return pRoot;
pRoot = pRoot.right;
}
}
return null;
}
}