Leetcode 173 二叉搜索树迭代器

解答一:

二叉搜索树很重要的特性:中序遍历是有序数列。

故可以将中序遍历存放在vector中,每次只要判断后面还是否有数则可得hasnext和next

 

代码:

class BSTIterator {
public:
    BSTIterator(TreeNode* root) {
        idx_ = 0;//数组始
        inOrder(root);
        end_ = vec_.size();//数组终
    }
    
    /** @return the next smallest number */
    int next() {
        return vec_[idx_++];
    }
    
    /** @return whether we have a next smallest number */
    bool hasNext() {
        return idx_ != end_;//注意has只是判断,不能更改idx
    }
private:
    void inOrder(TreeNode* root) {
        if (root != nullptr){
            inOrder(root->left);
            vec_.push_back(root->val);
            inOrder(root->right);
        } 
    }
private:
    std::vector<int> vec_;
    int idx_, end_;
};

 

解答二:

递归使得每次将一棵树的所有左分支入栈(即深度遍历,第一次遇到叶节点则停止)。栈顶就是当前最小元素,即所求的next。

出栈。进入该点右节点。重复上述操作,直至栈为空。

这里思想:只有左叶子会连续入栈。相当于栈手动模拟了递归。空间复杂度低于解答一。

class BSTIterator {
public:
    BSTIterator(TreeNode* root) {
        for (; root != nullptr; root = root->left) {
            sti_.push(root);
        }
    }
    
    /** @return the next smallest number */
    int next() {
        TreeNode* smallest = sti_.top();
        sti_.pop();
        int val = smallest->val;
        smallest = smallest->right;
        for (; smallest != nullptr; smallest = smallest->left) {
            sti_.push(smallest);
        }
        return val;
    }
    
    /** @return whether we have a next smallest number */
    bool hasNext() {
        return !sti_.empty();
    }
private:
    std::stack<TreeNode*> sti_;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值