• [leetode]Binary Search Tree Iterator


    用个stack模拟递归即可

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class BSTIterator {
    public:
        BSTIterator(TreeNode *root) {
            while(root) {
                st.push(root);
                root = root->left;
            }
        }
    
        /** @return whether we have a next smallest number */
        bool hasNext() {
            return !st.empty();
        }
    
        /** @return the next smallest number */
        int next() {
            TreeNode* top = st.top();
            int val = top->val;
            st.pop();
            top = top->right;
            while(top) {
                st.push(top);
                top = top->left;
            }
            return val;
        }
    private:
        stack<TreeNode*> st;
    };
    
    /**
     * Your BSTIterator will be called like this:
     * BSTIterator i = BSTIterator(root);
     * while (i.hasNext()) cout << i.next();
     */
  • 相关阅读:
    Json2JsonArray JsonArray2StringArray
    循环结构
    类型转换代码
    字符串的截取拼接
    循环语句,选择结构的相关代码
    Java代码2-运算符简单运用
    Java代码1
    集合框架
    接口
    继承多态
  • 原文地址:https://www.cnblogs.com/x1957/p/4196731.html
Copyright © 2020-2023  润新知