LeetCode - 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 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?
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public int kthSmallest(TreeNode root, int k) { Comparator<Integer> comparator = new Comparator<Integer>() { @Override public int compare(Integer s1, Integer s2) { return s2 - s1; } }; PriorityQueue<Integer> pq = new PriorityQueue<> (comparator); helper(root, k, pq); return pq.peek(); } public void helper(TreeNode root, int k, PriorityQueue<Integer> pq){ if (root == null) { return; } helper(root.left, k, pq); if (pq.size() < k) { pq.add(root.val); } else { if (root.val < pq.peek()) { pq.poll(); pq.add(root.val); } } helper(root.right, k, pq); } }
标签:pq,TreeNode,val,BST,int,Smallest,Kth,right,root 来源: https://www.cnblogs.com/incrediblechangshuo/p/12826570.html