GuilinDev

Lc0230

05 August 2008

230 Kth Smallest Element in BST

原题概述

Given a binary search tree, write a function

1
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:

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

Example 2:

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

Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

题意和分析

使用中序遍历,遍历到第k个元素就是第k小的,作为结果返回,因为BST的中序遍历的结果刚好是从小到大排列,同样,也可以通过递归和迭代来做。

代码

迭代解法,将k左子树的元素放入到stack中,如果不够k再放入右子树的元素,然后到k后就返回当前值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
 * 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) {
    Stack<TreeNode> stack = new Stack<>();

    TreeNode current = root;
    while(current != null || !stack.isEmpty()) {
      while (current != null) {
        stack.push(current);
        current = current.left;
      }
      current = stack.pop();
      k--;
      if (k == 0) {
        return current.val;
      }
      current = current.right; // here no need to push to stack
    }
    throw new IllegalArgumentException("There is no kth smallest element.");
  }
}

中序遍历,先递归左子树,当前结点做计算和判断,不够再递归右子树,到k个时返回即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int result = 0;
    int count = 0;
    public int kthSmallest(TreeNode root, int k) {
        count = k;
        inOrder(root);
        return result;
    }
    private void inOrder(TreeNode node) {
        if (node == null) {
            return;
        }
        
        inOrder(node.left); //中序先traverse先到leftmost
        
        count--;
        if (count == 0) {
            result = node.val;
            return;
        }
        inOrder(node.right);// 不夠再traverse右sub tree
    }
}