[LeetCode] Binary Search Tree Iterator
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<TreeNode*> 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 */
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· dotnet 源代码生成器分析器入门
· 官方的 MCP C# SDK:csharp-sdk
· 一款 .NET 开源、功能强大的远程连接管理工具,支持 RDP、VNC、SSH 等多种主流协议!
· 一文搞懂MCP协议与Function Call的区别
· 一次Java后端服务间歇性响应慢的问题排查记录