给定一个二叉搜索树的根节点 root ,和一个整数 k ,请你设计一个算法查找其中第 k 小的元素(从 1 开始计数)。
输入:根结点,整型变量
输出:二叉树结点的值
思路:使用中序遍历,遍历到的第k个数就是第k小的元素
/**
* 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 res = 0;
int count = 0;
public int kthSmallest(TreeNode root, int k) {
inorder(root, k);
return res;
}
public void inorder(TreeNode root, int k){
if(root == null){
return;
}
inorder(root.left, k);
if(k == count){
return;
}
if(++count == k){
res = root.val;
}
inorder(root.right, k);
}
}
if(k == count) return;
加入此行代码的原因是当遍历到第k个元素时,可以停止遍历,不用再加入其他的结点
二刷使用迭代法
class Solution {
public int kthSmallest(TreeNode root, int k) {
Deque<TreeNode> stack = new LinkedList<>();
while(root != null || !stack.isEmpty()){
while(root != null){
stack.push(root);
root = root.left;
}
root = stack.pop();
k--;
if(k == 0){
break;
}
root = root.right;
}
return root.val;
}
}
使用优先队列维护
/**
* 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> pq = new PriorityQueue<>((a, b) -> b-a);
Deque<TreeNode> stack = new LinkedList<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.poll();
if(pq.size() < k){
pq.add(node.val);
}else if(pq.peek() > node.val){
pq.poll();
pq.add(node.val);
}
if(node.left != null){
stack.push(node.left);
}
if(node.right != null){
stack.push(node.right);
}
}
return pq.peek();
}
}