剑指 Offer 54. 二叉搜索树的第k大节点
解法 中序遍历
通过右节点->根节点->左节点的顺序即可将二叉搜索树从大到小输出。可以通过一个计数器k进行计数当k为1时就到达了目标值。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int k;
public int kthLargest(TreeNode root, int k) {
if(root == null) return 0;
this.k = k;
return kthLargestCore(root);
}
private Integer kthLargestCore(TreeNode root) {
Integer target = null;
if(root.right != null)
target = kthLargestCore(root.right);
if (target == null) {
if (k == 1){
target = root.val;
}
k--;//k为值传递不能作为函数形参
}
if(target == null && root.left != null)
target = kthLargestCore(root.left);
return target;
}
}