Question

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

Thinking:

  • Method 1:Inorder traversal
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int kthSmallest(TreeNode root, int k) {
        if(root == null) return -1;
        List<Integer> result = new ArrayList<>();
        inorder(root, result, k);
        return result.get(k - 1);
    }
    private void inorder(TreeNode root, List<Integer> result, int k){
        if(root == null) return;
        inorder(root.left, result, k);
        result.add(root.val);
        if(result.size() == k) return;
        inorder(root.right, result, k);
    }
}

二刷

  1. The method of this question is to add all numbers into the list by inorder traversal.
  2. I added another quit point for recursive so it will significantly increase the efficiency.
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
     public int kthSmallest(TreeNode root, int k) {
         List<Integer> result = new LinkedList<>();
         inorder(result, root, k);
         return result.get(k - 1);
     }
     private void inorder(List<Integer> result, TreeNode node, int k){
         if(node == null || result.size() >= k){
             return;
         }
         inorder(result, node.left, k);
         result.add(node.val);
         inorder(result, node.right, k);
     }
    }