Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0 Star 0 Fork 0

徐云天/leetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
_230.java 1.69 KB
一键复制 编辑 原始数据 按行查看 历史
徐云天 提交于 2021-06-11 11:15 +08:00 . 增加230
import java.util.ArrayDeque;
import java.util.Deque;
// 2中解法: 1.中序遍历递归写法 2.非递归写法
public class _230 {
static 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;
}
}
static class Solution1 {
public int kthSmallest(TreeNode root, int k) {
int[] p = new int[2];
inOrder(root, p, k);
return p[1];
}
public void inOrder(TreeNode root, int[] p, int k) {
if (root == null) return;
inOrder(root.left, p, k);
if (p[0] < k) {
p[0]++;
p[1] = root.val;
} else if (p[0] == k) {
return;
}
inOrder(root.right, p, k);
}
}
static class Solution2 {
public int kthSmallest(TreeNode root, int k) {
Deque<TreeNode> stack = new ArrayDeque<>();
int count = 0;
Integer val = null;
while (root != null || !stack.isEmpty()) {
if (root == null || root.left == null) {
if (root == null) root = stack.pop();
val = root.val;
count++;
root = root.right;
if (count == k) return val;
continue;
}
stack.push(root);
root = root.left;
}
return val;
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/xuyuntian/leetcode.git
git@gitee.com:xuyuntian/leetcode.git
xuyuntian
leetcode
leetcode
master