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.
采用中序遍历将节点压入栈中,由于要求存储空间为O(h),因此不能在一开始将所有节点全部压入,只是压入最左边一列。当取出一个节点时,压入其右子节点的所有左节点。
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 private: 12 stack <TreeNode*> stk; 13 int minres; 14 public: 15 BSTIterator(TreeNode *root) { 16 while(root) 17 { 18 stk.push(root); 19 root=root->left; 20 } 21 } 22 23 /** @return whether we have a next smallest number */ 24 bool hasNext() { 25 if(stk.empty()) 26 return false; 27 TreeNode* top; 28 top=stk.top(); 29 minres=top->val; 30 stk.pop(); 31 TreeNode* cur=top->right; 32 if(cur) 33 { 34 stk.push(cur); 35 cur=cur->left; 36 while(cur) 37 { 38 stk.push(cur); 39 cur=cur->left; 40 } 41 } 42 return true; 43 } 44 45 /** @return the next smallest number */ 46 int next() { 47 return minres; 48 } 49 }; 50 51 /** 52 * Your BSTIterator will be called like this: 53 * BSTIterator i = BSTIterator(root); 54 * while (i.hasNext()) cout << i.next(); 55 */
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了