[LeetCode] 173. Binary Search Tree Iterator

思路:
用一个stack记录左节点. 上来先把整个树的最左一流节点push到栈中. 如果要看是否有下一个节点, 那么就看栈是否空, 如果要得到下一个节点的数值, 就把栈顶的元素返回出去, 并且把栈顶的树的右节点的左边一流节点push到栈中. 这样其实空间是O(h)的, next()函数的最坏时间复杂度也是O(h), 但平均时间开销是O(1), 符合题目要求.

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

    /** @return whether we have a next smallest number */
    bool hasNext() {
        return ! s.empty();
    }

    /** @return the next smallest number */
    int next() {
        TreeNode* cur = s.top();
        s.pop();
        TreeNode* temp = cur->right;
        while (temp) {
            s.push(temp);
            temp = temp->left;
        }
        return cur->val;    
    }
private:
    stack<TreeNode*> s;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值