【Leetcode刷题篇】leetcode230 二叉搜索树中第K小的元素
发布日期:2021-06-29 15:33:27 浏览次数:3 分类:技术文章

本文共 1081 字,大约阅读时间需要 3 分钟。

题目:给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。

说明:

你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。

在这里插入图片描述

思路1:递归方式

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; } } // 递归 public int kthSmallest(TreeNode root, int k) {
ArrayList
res = new ArrayList<>(); res = inorder(root,res); return res.get(k-1); } // 存储 private ArrayList
inorder(TreeNode root,ArrayList
res){
if(root==null) {
return res; } // 左子树 inorder(root.left,res); // 当前节点的值处理 res.add(root.val); // 右子树 inorder(root.right,res); return res; }

思路2:迭代方式

// 迭代	 public int kthSmallest_2(TreeNode root, int k) {
Stack
stack = new Stack<>(); while(true) {
while(root!=null) {
stack.push(root); root = root.left; } root = stack.pop(); if(--k==0) {
return root.val; } root = root.right; } }

转载地址:https://codingchaozhang.blog.csdn.net/article/details/109494694 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:【Leetcode刷题篇】leetcode173 二叉搜索树迭代器
下一篇:【Leetcode刷题篇】leetcode236 二叉树的最近公共祖先

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年04月15日 14时54分14秒