173. Binary Search Tree Iterator
来源:互联网 发布:备考注册会计师 知乎 编辑:程序博客网 时间:2024/06/07 14:27
利用stack完成树的中序遍历。stack沿着树一直向左走,当走不下去了。
如果结点有右孩子,那么读取top后放入右孩子。然后沿着右孩子向左走,一直走到没有左孩子了为止。
如果没有右孩子,直接读取top。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class BSTIterator {private: stack<TreeNode *> findNext;public: BSTIterator(TreeNode *root) { findNext.push(root); while(findNext.top()!=NULL) { TreeNode *temp=findNext.top(); findNext.push(temp->left); } findNext.pop(); } /** @return whether we have a next smallest number */ bool hasNext() { return (!findNext.empty()); } /** @return the next smallest number */ int next() { TreeNode *temp=findNext.top(); if(temp->right!=NULL) { findNext.pop(); findNext.push(temp->right); while(findNext.top()!=NULL) { TreeNode *temp=findNext.top(); findNext.push(temp->left); } findNext.pop(); } else { findNext.pop(); } return temp->val; }};/** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */
0 0
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator**
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 402. Remove K Digits
- 5.正则以及排序算法
- [面试][oracle]详述Oracle RAC的五大优势及其劣势
- PAT--1127. ZigZagging on a Tree
- spring mvc基础篇(一):入门案例
- 173. Binary Search Tree Iterator
- Redis学习笔记整理
- 自然语言处理入门学习之一:安装nltk包&&虚拟机界面太小&&ubuntu中文输入法安装
- 谷哥的小弟学后台(29)——动态代理
- 你的Toast也可以定制
- Java NIO笔记之IO基础概念
- HDU1258&&ZOJ1711-Sum It Up
- ORA-16179: incremental changes to "log_archive_dest_31" not allowed with SPFILE
- [面试][oracle] 数据库去重的三种方法: