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

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

The key to this problem is to store the values in a stack. In the constructor and next, we add all the next smallest nodes into the stack. The following code should be obvious after you run it on some examples.

1 /** 2  * Definition for binary tree 3  * struct TreeNode { 4  *     int val; 5  *     TreeNode *left; 6  *     TreeNode *right; 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10 class BSTIterator {11 public:12     BSTIterator(TreeNode *root) {13         pushLeft(root);14     }15 16     /** @return whether we have a next smallest number */17     bool hasNext() {18         return !nodes.empty();19     }20 21     /** @return the next smallest number */22     int next() {23         TreeNode* node = nodes.top();24         nodes.pop();25         pushLeft(node -> right);26         return node -> val;27     }28 private:29     stack
nodes;30 void pushLeft(TreeNode* node) {31 while (node) {32 nodes.push(node);33 node = node -> left;34 }35 }36 };37 38 /**39 * Your BSTIterator will be called like this:40 * BSTIterator i = BSTIterator(root);41 * while (i.hasNext()) cout << i.next();42 */

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4630057.html

你可能感兴趣的文章
SQL Mirror配置手册
查看>>
linux bash bc awk 浮点 计算 比较
查看>>
基于socket.io的实时消息推送
查看>>
软件测试主要是做什么?
查看>>
7月第二周搜索引擎网站排名:百度谷歌搜搜前三
查看>>
查询进程并杀死
查看>>
VMXNET3 vs E1000E and E1000
查看>>
7200的GRE(隧道)+ipsec(传输模式+pre-share)配置
查看>>
四、编译安装php-5.5.34
查看>>
Thinkpad X240修改bios引导,U盘安装系统
查看>>
Slave SQL: Relay log read failure: Could not parse relay log event entry.
查看>>
抽取Zabbix的图形整合到自己后台
查看>>
lamp服务器站点目录被植入广告代码
查看>>
如何把海量数据从 Oracle 导入到 Mongodb
查看>>
rsync后台服务
查看>>
awk 比较两个文件的异同
查看>>
Centos7.0下部署Rsync+inotify实时同步
查看>>
通过rsync+inotify实现数据的实时备份
查看>>
我的友情链接
查看>>
Linux输入子系统
查看>>