173. Binary Search Tree Iterator(二叉查找树迭代器)的C++解法

题目描述:https://www.lintcode.com/problem/binary-search-tree-iterator/description
利用栈:

class BSTIterator {
public:
    stack<TreeNode *> myStack;
    TreeNode *current;
    
    BSTIterator(TreeNode *root) {
        while (!myStack.empty()) {
            myStack.pop();
        }
        current = root;
    }

    bool hasNext() {
        return (current != NULL || !myStack.empty());
    }

    /** @return the next smallest number */
    TreeNode* next() {
        while (current != NULL) {
            myStack.push(current);
            current = current->left;
        }//从当前节点一路向左到头就是最小的;
        current = myStack.top(); myStack.pop();
        TreeNode *nxt = current;
        //为下一个最小值做准备,当前已经到最左边了,下一个点将在这个点的右子树中出现
        current = current->right;
        return nxt;
    }
};

题目要求空间复杂度为O(h),h是二叉查找树的深度,因此考虑每次只放一部分树的结点入栈。首先我们知道根的左子树的左子树的左子树...一直到最左的左子树L一定是最小值,那么先把这部分压入栈,栈顶元素L就是最小值。而下一个最小值,有可能是这个结点的右子树(根L->right,或者根的左子树L->right->.....left),那么把这部分压入栈中;如果没有的话就向上找L->father(树的结构里没有这个值但是栈中已经保存了)。
图形解释可以看这篇博客。

class BSTIterator {
public:
    stack<TreeNode *> s;
    BSTIterator(TreeNode *root) {
        while(root!=NULL)
       {
           s.push(root);
           root=root->left;
       }
    }
    bool hasNext() {
        if (s.empty()) return false;
        else return true;
    }
    int next() {
        TreeNode * res=s.top();
        s.pop();
        TreeNode * tmp=res->right;
        while (tmp!=NULL)
        {
            s.push(tmp);
            tmp=tmp->left;
        }
        return res->val;
    }
};
  • 还有要求空间复杂度为O(1)的,我想可以参考Morris算法。Morris算法主要利用了叶子节点的左右子树均为空的特性,构建一个从叶子到根的回路来代替栈。

另一种理解方法:

class BSTIterator {
public:
    stack<TreeNode *> myStack;
    TreeNode *current;
    
    BSTIterator(TreeNode *root) {
        while (!myStack.empty()) {
            myStack.pop();
        }
        current = root;
    }

    bool hasNext() {
        return (current != NULL || !myStack.empty());
    }

    /** @return the next smallest number */
    TreeNode* next() {
        while (current != NULL) {
            myStack.push(current);
            current = current->left;
        }//从当前节点一路向左到头就是最小的;
        current = myStack.top(); myStack.pop();
        TreeNode *nxt = current;
        //为下一个最小值做准备,当前已经到最左边了,下一个点将在这个点的右子树中出现
        current = current->right;
        return nxt;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值