剑指 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 ≤ 二叉搜索树元素个数

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     int count=0;
12     public TreeNode helper(TreeNode root, int k){
13         if(root!=null){
14            TreeNode node=helper(root.right,k);
15            if(node!=null) return node;
16            count++;
17            if(count==k) return root;
18            node=helper(root.left,k);
19            if(node!=null){
20                return node;
21            }
22        }
23        return null;
24     }
25     public int kthLargest(TreeNode root, int k) {
26        TreeNode t=helper(root,k);
27        if(t!=null) return t.val;
28        return -1;
29     }
30 }
原文地址:https://www.cnblogs.com/Susie2world/p/13368153.html