LeetCode173——Binary Search Tree Iterator


终于进入了中等难度的题目了。貌似leetcode不停地加题量,要做完正的是不那么容易啊。新年开工,小伙伴们都在晒红包,深圳这边 上班第一天一般都有发红包,不知道其他地方的是不是也这样。

到目前为止,做了40题了,不得不感慨,算法有待提高。大学真是白过了,人生那么美好的四年白过了,这是多么的悲哀。 现在想想,一个人要想在大学过得有意义,对以后的人生打下坚实的基础,那么最迟在大学一年之后,一定要有较广的见识,对社会有充分 的认识。总之,足够的广阔视野,才能让你知道当前的路怎么走。现实呢,大学专业往往都是父母帮填的,学生自己对专业是一无所知, 以至于进入大学后,不知道从何学起,如何学习,于是陷入漫长的迷茫期。当看清前路时,发现毕业来临了。

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.

Credits:

Special thanks to @ts for adding this problem and creating all test cases.

难度系数:

中等

实现

class BSTIterator {
public:
     BSTIterator(TreeNode *root) {
        pos = 0;
        vector<TreeNode*> stack;
        if (root) {
            stack.push_back(root);
        }
        bool down = true;
        while (!stack.empty()) {
            TreeNode* node = stack.back();
            if (node->left != NULL && down) {
                stack.push_back(node->left);
            } else {
                down = false;
                nv.push_back(node->val);
                stack.pop_back();
                if (node->right) {
                    stack.push_back(node->right);
                    down = true;
                }
            }
        }
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
        return pos < nv.size();
    }

    /** @return the next smallest number */
    int next() {
        return nv[pos++];
    }
private:
    int pos;
    vector<int> nv;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值