1. 程式人生 > 實用技巧 >劍指 Offer 54. 二叉搜尋樹的第k大節點

劍指 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 }