leetcode-230. 二叉搜索树中第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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
class Solution { public int kthSmallest(TreeNode root, int k) { Queue<Integer> queue = new PriorityQueue<>(k, (o1, o2) -> { return o1 - o2; });
dfs(root, queue);
int res = -1; while(true){ int v = queue.poll(); k--;
if(k == 0){ res = v; } if( k <= 0){ break; } }
return res; }
public void dfs(TreeNode root, Queue<Integer> queue){ if(root == null){ return; } queue.offer(root.val);
dfs(root.left, queue); dfs(root.right, queue); } }
|