C++ recursive innode traverse


  • 0
    class BSTIterator {
        stack<TreeNode*> stk;
        TreeNode *cur;
    public:
        BSTIterator(TreeNode *root) {
            TreeNode *tmp = root;
            while(tmp!=nullptr) {
                stk.push(tmp);
                tmp = tmp->left;
            }
        }
    
        /** @return whether we have a next smallest number */
        bool hasNext() {
            if(stk.empty()) return false;
            cur = nullptr;
            TreeNode *tmp;
            if(!stk.empty()){
                cur = stk.top();
                stk.pop();
                tmp = cur->right;
            }
            while(tmp) {
                stk.push(tmp);
                tmp = tmp->left;
            }
            return true;
        }
    
        /** @return the next smallest number */
        int next() {
            return cur->val;
        }
    };
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.