LeetCode-Kth Smallest Element in a BST

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/88170924

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);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/88170924
今日推荐