230. Kth Smallest Element in a BST

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Note: 
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

Example 1:

Input: root = [3,1,4,null,2], k = 1
   3
  / \
 1   4
  \
   2
Output: 1

Example 2:

Input: root = [5,3,6,2,4,null,null,1], k = 3
       5
      / \
     3   6
    / \
   2   4
  /
 1
Output: 3

 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 public class Solution {
11     public int kthSmallest(TreeNode root, int k) {
12         int[] arr = new int[2];
13         helper(root, arr, k);
14         return arr[1];
15     }
16     
17     public void helper(TreeNode root, int[] arr, int k) {
18         if (root != null) {
19             helper(root.left, arr, k);
20             arr[0]++;
21             if (arr[0] == k) {
22                 arr[1] = root.val;
23                 return;
24             }
25             helper(root.right, arr, k);
26         }
27     }
28 }

 

posted @ 2019-04-28 12:46  北叶青藤  阅读(213)  评论(0)    收藏  举报