zoukankan      html  css  js  c++  java
  • 173. Binary Search Tree Iterator

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class BSTIterator {
    public:
        stack<TreeNode *> s;
        TreeNode *p;
        BSTIterator(TreeNode *root) {
            p = root;
        }
    
        /** @return whether we have a next smallest number */
        bool hasNext() {
            return p != NULL || !s.empty();
        }
    
        /** @return the next smallest number */
        int next() {
            if (hasNext()) {
                while (p) {
                    s.push(p);
                    p = p->left;
                }
                p = s.top();
                s.pop();
                int val = p->val;
                p = p->right;
                return val;
            }
            return -1;
        }
    };
    
    /**
     * Your BSTIterator will be called like this:
     * BSTIterator i = BSTIterator(root);
     * while (i.hasNext()) cout << i.next();
     */
    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class BSTIterator {
    public:
        stack<TreeNode *> s;
        BSTIterator(TreeNode *root) {
            while (root) {
                s.push(root);
                root = root->left;
            }
        }
    
        /** @return whether we have a next smallest number */
        bool hasNext() {
            return !s.empty();
        }
    
        /** @return the next smallest number */
        int next() {
            if (hasNext()) {
                TreeNode* p = s.top();
                s.pop();
                int val = p->val;
                p = p->right;
                while (p) {
                    s.push(p);
                    p = p->left;
                }
                return val;
            }
            return -1;
        }
    };
    
    /**
     * Your BSTIterator will be called like this:
     * BSTIterator i = BSTIterator(root);
     * while (i.hasNext()) cout << i.next();
     */
  • 相关阅读:
    Linux下如何查看哪些进程占用的CPU内存资源最多
    linux查看端口占用情况
    oracle11g用户名密码不区分大小写
    oracle表导入导出
    Oracle的实例占用内存调整
    修改oracle内存
    ORA-04031: 无法分配 共享内存
    OCI_INVALID_HANDLE 什么原因
    Android SDK Manager国内无法更新的解决方案
    sqlite3增删改查简单封装
  • 原文地址:https://www.cnblogs.com/JTechRoad/p/9065638.html
Copyright © 2011-2022 走看看