【Leetcode刷题篇】leetcode173 二叉搜索树迭代器
发布日期:2021-06-29 15:33:27 浏览次数:2 分类:技术文章

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

题目:实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。

调用 next() 将返回二叉搜索树中的下一个最小的数。

在这里插入图片描述

题解一、对其进行遍历,存储

class TreeNode{
int val; TreeNode left; TreeNode right; TreeNode(int x){
val = x; } } class BSTIterator {
int index; ArrayList
list; public BSTIterator(TreeNode root) {
this.list = new ArrayList<>(); this.index = -1; this.inorder(root); } // 先进行中序遍历 private void inorder(TreeNode root){
if(root==null){
return; } inorder(root.left); list.add(root.val); inorder(root.right); } /** @return the next smallest number */ public int next() {
return list.get(++index); } /** @return whether we have a next smallest number */ public boolean hasNext() {
return this.index+1 < this.list.size(); } }

对其进行用栈来存储

class BSTIterator {
// 栈 Stack
stack; public BSTIterator(TreeNode root) {
// 初始化 stack = new Stack<>(); this.pre(root); } // 先存储一部分值 private void pre(TreeNode root){
while(root!=null){
stack.push(root); root = root.left; } } /** @return the next smallest number */ public int next() {
TreeNode temp = this.stack.pop(); if(temp.right!=null){
this.pre(temp.right); } return temp.val; } /** @return whether we have a next smallest number */ public boolean hasNext() {
return this.stack.size()>0; } }

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

上一篇:【Leetcode刷题篇】leetcode99 恢复二叉搜索树
下一篇:【Leetcode刷题篇】leetcode230 二叉搜索树中第K小的元素

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月09日 13时18分57秒