[LeetCode] Binary Search Tree Iterator

本文介绍了一种使用栈来实现二叉搜索树迭代器的方法,通过将所有左子节点压入栈中,可以有效地按顺序访问每个节点的值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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  */

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值