天天看點

LeetCode-Kth Smallest Element in a BST

Description:

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
           

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大/小的元素,根據所給元素構造最大/小堆,移出k-1個堆頂元素,那麼最後堆頂的元素就是所求的結果;

Java
/**
 * 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) {
        Queue<Integer> heap = new PriorityQueue<>((a, b) -> a - b);
        traverseTree(root, heap);
        while (k-- > 1) {
            heap.poll();
        }
        
        return heap.peek();
    }
    
    private void traverseTree(TreeNode root, Queue<Integer> heap) {
        if (root == null) return;
        heap.add(root.val);
        traverseTree(root.left, heap);
        traverseTree(root.right, heap);
    }
}
           

解法二:因為題目中給定的是一顆二叉搜尋樹,那麼中序周遊得到的序列就是按照非降序排序的結果,此時,隻需要傳回指定位置的元素即可;

Java
/**
 * 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> value = new ArrayList<>();
        inorderTraverse(root, value);
        return value.get(k - 1);
    }
    
    private void inorderTraverse(TreeNode root, List<Integer> value) {
        if (root == null) {
            return;
        }
        inorderTraverse(root.left, value);
        value.add(root.val);
        inorderTraverse(root.right, value);
    }
}