剑指 Offer 54. 二叉搜索树的第k大节点
给定一棵二叉搜索树,请找出其中第 k 大的节点的值。
示例 1:
输入: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
输出: 4
示例 2:
输入: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
输出: 4
限制:
1 ≤ k ≤ 二叉搜索树元素个数
题解
Code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int kthLargest(TreeNode root, int k) {
if(root == null || k <= 0){
return 0;
}
int rightCount = nodeCount(root.right);
if(rightCount + 1 == k){
return root.val;
}else if(rightCount >= k){
return kthLargest(root.right, k);
}else{
return kthLargest(root.left, k - rightCount - 1);
}
}
public int nodeCount(TreeNode root){
if(root == null){
return 0;
}
return nodeCount(root.left) + nodeCount(root.right) + 1;
}
}