博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Binary Search Tree Iterator
阅读量:4074 次
发布时间:2019-05-25

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

Binary Search Tree Iterator

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

Calling next() will return the next smallest number in the BST.

Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.

Java代码;

public class BSTIterator {    private Stack
stack; public BSTIterator(TreeNode root) { stack = new Stack
(); TreeNode tempNode = root; if(root!=null) { while(tempNode != null){ stack.push(tempNode); tempNode = tempNode.left; } } } /** @return whether we have a next smallest number */ public boolean hasNext() { return !stack.empty(); } /** @return the next smallest number */ public int next() { TreeNode node = stack.pop(); TreeNode tempNode = node.right; if(tempNode!=null){ while(tempNode!=null){ stack.push(tempNode); tempNode = tempNode.left; } } return node.val; }}
 

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

你可能感兴趣的文章
【数据结构周周练】008 二叉树的链式创建及测试
查看>>
《软件体系结构》 第九章 软件体系结构评估
查看>>
《软件体系结构》 第十章 软件产品线体系结构
查看>>
《软件过程管理》 第六章 软件过程的项目管理
查看>>
《软件过程管理》 第九章 软件过程的评估和改进
查看>>
分治法 动态规划法 贪心法 回溯法 小结
查看>>
《软件体系结构》 练习题
查看>>
《数据库系统概论》 第一章 绪论
查看>>
《数据库系统概论》 第二章 关系数据库
查看>>
《数据库系统概论》 第三章 关系数据库标准语言SQL
查看>>
SQL语句(二)查询语句
查看>>
SQL语句(六) 自主存取控制
查看>>
《计算机网络》第五章 运输层 ——TCP和UDP 可靠传输原理 TCP流量控制 拥塞控制 连接管理
查看>>
堆排序完整版,含注释
查看>>
二叉树深度优先遍历和广度优先遍历
查看>>
生产者消费者模型,循环队列实现
查看>>
PostgreSQL代码分析,查询优化部分,process_duplicate_ors
查看>>
PostgreSQL代码分析,查询优化部分,canonicalize_qual
查看>>
PostgreSQL代码分析,查询优化部分,pull_ands()和pull_ors()
查看>>
IA32时钟周期的一些内容
查看>>