【剑指Offer】二叉搜索树的第k个结点

题目

给定一棵二叉搜索树,请找出其中的第k大的结点。

实现

1
2
3
4
5
6
7
8
9
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;
}
}
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
private int count = 0;

public TreeNode KthNode(TreeNode pRoot, int k) {
if (pRoot == null || k < 1)
return null;

return KthNodeHelper(pRoot, k);
}

private TreeNode KthNodeHelper(TreeNode root, int k) {
if (root == null)
return null;

TreeNode node = KthNodeHelper(root.left, k);

if (node != null)
return node;

if (++count == k)
return root;

node = KthNodeHelper(root.right, k);

if (node != null)
return node;

return null;
}