【LEETCODE】173-Binary Search Tree Iterator
2015-11-05 14:48
447 查看
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.
参考: https://github.com/kamyu104/LeetCode/blob/master/Python/binary-search-tree-iterator.py
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.
参考: https://github.com/kamyu104/LeetCode/blob/master/Python/binary-search-tree-iterator.py
# Definition for a binary tree node # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class BSTIterator(object): def __init__(self, root): """ :type root: TreeNode """ self.stack=[] #记录cur的轨迹 self.cur=root #从root起,先走左child,一直到leave层 def hasNext(self): """ :rtype: bool """ return self.stack or self.cur #当stack和cur都为空的时候,是已经从leave到达最right的root了 def next(self): """ :rtype: int """ while self.cur: self.stack.append(self.cur) self.cur=self.cur.left self.cur=self.stack.pop() node=self.cur self.cur=self.cur.right return node.val #append到v上 # Your BSTIterator will be called like this: # i, v = BSTIterator(root), [] # while i.hasNext(): v.append(i.next())
相关文章推荐
- 黑马程序员——JAVA基础----集合框架(三)
- Oracle细节总结(一)
- ADT
- linux:预定义变量和read命令
- 在WPF中自定义你的绘制(二)
- 在WPF中自定义你的绘制(一)
- OSVERSIONINFO的用法及实例
- gcc 库的链接顺序问题
- Lua1.1 Lua 的参考手册 (二)
- Hibernate.cfg.xml配置文件结构详解
- mysqlbinlog使用
- SQL基本语句汇总
- Linux网络编程常用API(一)
- wordpress注册加上问题验证
- express.Router创建模块化路由
- Lua1.1 Lua 的参考手册 (一)
- 享元模式 -- 大话设计模式
- 图文详解Windows Server2012 R2中安装SQL Server2008
- iOS反射的基本应用
- redist技术