leetcode173 二叉搜索树迭代器

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
private:
    stack<TreeNode*> s;
    
public:
    BSTIterator(TreeNode* root) {
        find_left(root);
        
    }
    
    /** @return the next smallest number */
    int next() {
        TreeNode* tmp = s.top();
        s.pop();
        if(tmp->right!=nullptr)  //如果有右子树,下一个点应该是右子树最左边的点,如果无右子树下一个点应该是其父节点,即栈顶元素
            find_left(tmp->right);
        return tmp->val;
        
    }
    
    /** @return whether we have a next smallest number */
    bool hasNext() {
        if(s.empty())
            return false;
        return true;
        
    }
    
    void find_left(TreeNode* root) //找当前节点最左边的结点并一路压栈
    {
        
        while (root!=nullptr)
        {
            s.push(root);
            root = root->left;
        }
    }
};

中序遍历二叉搜索树得到排序的序列

对一个结点来说,将左边的入栈,弹栈,如果有右子树对右子树重复上述步骤,如果没有右子树继续弹栈。
转自:
https://leetcode.com/problems/binary-search-tree-iterator/discuss/52519/My-Solution-in-C%2B%2B-in-average-O(1)-time-and-uses-O(h)-memory

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值