一、题目内容

image.png

二、题解

解法1:

思路

二叉搜索树,中序遍历则为从小到大,中序遍历的倒叙,则为从大到小

代码

  1. class Solution {
  2. private int currIndex = 0;
  3. private int res;
  4. public int kthLargest(TreeNode root, int k) {
  5. currIndex = k;
  6. recur(root);
  7. return res;
  8. }
  9. private void recur(TreeNode root){
  10. if(root == null){
  11. return;
  12. }
  13. recur(root.right);
  14. if(currIndex == 0){
  15. return;
  16. }
  17. if(--currIndex == 0) {
  18. res = root.val;
  19. }
  20. recur(root.left);
  21. }
  22. }