题目链接
题目描述
给定一棵二叉搜索树,请找出其中第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 ≤ 二叉搜索树元素个数
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目分析
1、本题的坑点在于第K大,它的意思就是遍历树的时候按照右根左的顺序进行遍历
2、设置一个全局变量count,将其值置为k,进行递减,等到减为1的时候就为目标
通过代码
class Solution {
int count=0;
int res=0;
public int kthLargest(TreeNode root, int k) {
count=k;
find(root);
return res;
}
public void find(TreeNode root){
if (root!=null){
find(root.right);
if (count==1) {
if (res!=0) return;
res=root.val;
return ;
}
count--;
find(root.left);
}else return;
}
}