
7

#yyds干货盘点# LeetCode 腾讯精选练习 50 题:二叉搜索树中第K小的元素
source link: https://blog.51cto.com/u_13321676/5868908
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

#yyds干货盘点# LeetCode 腾讯精选练习 50 题:二叉搜索树中第K小的元素
精选 原创给定一个二叉搜索树的根节点 root ,和一个整数 k ,请你设计一个算法查找其中第 k 个最小元素(从 1 开始计数)。
输入:root = [3,1,4,null,2], k = 1
输入:root = [5,3,6,2,4,null,null,1], k = 3
代码实现:
class Solution {
public int kthSmallest(TreeNode root, int k) {
Deque<TreeNode> stack = new ArrayDeque<TreeNode>();
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;
}
}
public int kthSmallest(TreeNode root, int k) {
Deque<TreeNode> stack = new ArrayDeque<TreeNode>();
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;
}
}
- 赞
- 收藏
- 评论
- 分享
- 举报
</div
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK