给定一棵二叉搜索树,请找出其中第 k 大的节点的值。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
private TreeNode ans = null;
private int solve(TreeNode root, int k) {
if (root == null) {
return 0;
}
int right = solve(root.right, k);
if (ans != null) {
return 0;
}
if (right == k - 1) {
ans = root;
return 0;
}
int left = solve(root.left, k - right - 1);
return left + right + 1;
}
public int kthLargest(TreeNode root, int k) {
solve(root, k);
return ans.val;
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}