解题思路来自评论区的大佬:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
/*
解题思路:中序遍历后的数就是排好序的(从大到小排序的),我们只需要储存第三个值就可以了
切记,树要判断节点为空的情况,且尽量在遍历函数里判断
*/
int count = 0;
int res = 0;
public int kthLargest(TreeNode root, int k) {
//将k的值赋值给count
count=k;
//利用中序遍历求解
LDR(root);
//返回最终结果
return res;
}
public void LDR(TreeNode root){
if(root.right != null && count>0 ) LDR(root.right);
count--;
if(count==0){
res = root.val;
return;
}
if(root.left != null && count>0 ) LDR(root.left);
}
}