博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【Leetcode刷题篇】leetcode173 二叉搜索树迭代器
阅读量:1887 次
发布时间:2019-04-26

本文共 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; } }

转载地址:http://owwdf.baihongyu.com/

你可能感兴趣的文章
自我学习37:请描述一下网页从开始请求到最后展示的完整过程
查看>>
自我学习38:如何区分前后端BUG
查看>>
自我学习39:接口自动化测试用例&功能测试用例区别
查看>>
mirror去兔子补丁下载 附安装教程
查看>>
mirror去兔子补丁 v3.0附安装教程
查看>>
mirror去兔子补丁为什么还有兔子_mirror去兔子补丁使用教程
查看>>
3dmax2012安装教程
查看>>
OC渲染器(Octane Render)整合版安装包 附安装教程
查看>>
操作系统期末大题复习
查看>>
hive:分区表,hbase外表
查看>>
想要成为运维,想要成为后期的架构师?这些知识是必备的!
查看>>
linux 是如何 快速一键安装禅道的呐?
查看>>
运维面试基础试题(四)
查看>>
一键安装Openstack单节点 必能成功
查看>>
面试紧张怎么办
查看>>
关系型数据库 ,nosql数据库简介
查看>>
Centos 7搭建NTP时间同步服务器
查看>>
centos7 基于rsync+inotify 实现定时备份
查看>>
指定IP进行 文件的分发
查看>>
基于http搭建本地yum仓库
查看>>