Leetcode-173. 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.

思路

这道题本质上是写一个二叉树的中序遍历的迭代器。内部设置一个栈,初始化的时候,存储从根节点到最左叶子节点的路径。在遍历的过程中,每次从栈中弹出一个元素,作为当前的返回结果,同时探测一下当前节点是否存在右孩子,如果有,则进入右孩子,并把从该右孩子到最左叶子节点的所有节点入栈。

代码

class BSTIterator {
public:
    BSTIterator(TreeNode *root) {
        while(root) {
            ss.push(root);
            root = root->left;
        }
    }

    bool hasNext() {
        return !ss.empty();
    }

    int next() {
        TreeNode *t = ss.top();
        ss.pop();
        if(t->right) {
            TreeNode *p = t->right;
            while(p) {
                ss.push(p);
                p = p->left;
            }
        }
        return t->val;
    }
private:
    stack<TreeNode*> ss;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值