LC.P230[二叉搜索树中第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
/**
* 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) {
PriorityQueue<Integer> q = new PriorityQueue<>();
preOrder(root, q);
while (--k > 0) q.poll();
return q.peek();
}

private void preOrder(TreeNode root, PriorityQueue<Integer> q) {
if (root == null) return;
q.offer(root.val);
preOrder(root.left, q);
preOrder(root.right, q);
}
}
  • 时间复杂度:$O(nlogn)$
  • 空间复杂度:$O(n)$

方法二:中序遍历

利用二叉搜索树的中序遍历为递增序列这一特点,对树进行中序遍历计数。

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() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int ans, k;

public int kthSmallest(TreeNode root, int k) {
this.k = k;
inOrder(root);
return ans;
}

private void inOrder(TreeNode root) {
if (root == null) return;
inOrder(root.left);
if (k == 0) return;
if (--k == 0) ans = root.val;
inOrder(root.right);
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$