给定一棵二叉搜索树,请找出其中第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 static int count=0; 12 static int res=0; 13 public int kthLargest(TreeNode root, int k) { 14 count=0; 15 max_k(root,k); 16 return res; 17 } 18 public static void max_k(TreeNode root,int k){ 19 //考察第k大的,先进右子树,第k小的,进左子树先 count!=k,条件时避免已经找到还继续递归下去 20 if(count!=k&&root.right!=null){ 21 max_k(root.right,k); 22 } 23 //判断当前结点是否时第k大 24 if(count!=k){ 25 count++; 26 if(count==k){ 27 res=root.val; 28 } 29 } 30 31 if(count!=k&&root.left!=null){ 32 max_k(root.left,k); 33 } 34 35 36 } 37 }
原文:https://www.cnblogs.com/SEU-ZCY/p/14641974.html