2021.10.17 - 124.二叉搜索树中第K小的元素
作者:互联网
文章目录
1. 题目
2. 思路
(1) 中序遍历+递归
- 中序遍历二叉搜索树,每遍历一个结点,k减1,当k为0时,该结点的值即为第k个最小元素。
(2) 中序遍历+栈
- 与(1)的思路基本相同,利用栈代替递归实现中序遍历。
3. 代码
import java.util.Deque;
import java.util.LinkedList;
public class Test {
public static void main(String[] args) {
}
}
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 {
private int k = 0;
private int res = -1;
public int kthSmallest(TreeNode root, int k) {
this.k = k;
inorder(root);
return res;
}
private void inorder(TreeNode root) {
if (root == null || res >= 0) {
return;
}
inorder(root.left);
k--;
if (k == 0) {
res = root.val;
}
inorder(root.right);
}
}
class Solution1 {
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;
}
}
标签:遍历,TreeNode,2021.10,17,int,val,124,right,root 来源: https://blog.csdn.net/qq_44021223/article/details/120808084