首页 > 其他 > 详细

剑指 Offer 54. 二叉搜索树的第k大节点

时间:2020-07-23 22:16:49      阅读:79      评论:0      收藏:0      [点我收藏+]

给定一棵二叉搜索树,请找出其中第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 }

 

剑指 Offer 54. 二叉搜索树的第k大节点

原文:https://www.cnblogs.com/Susie2world/p/13368153.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!