7

#yyds干货盘点# LeetCode 腾讯精选练习 50 题:二叉搜索树中第K小的元素

 2 years ago
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.
neoserver,ios ssh client

#yyds干货盘点# LeetCode 腾讯精选练习 50 题:二叉搜索树中第K小的元素

精选 原创

灰太狼_cxh 2022-11-18 18:29:51 博主文章分类:leetcode ©著作权

文章标签 二叉搜索树 代码实现 文章分类 Java 编程语言 阅读数455

给定一个二叉搜索树的根节点 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;
}
}
  • 收藏
  • 评论
  • 分享
  • 举报

</div


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK