Leetcode 173 binary search tree iterator

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/Mr_zhuo_/article/details/88591776

Solution one:

Binary search tree very important feature: preorder is an ordered sequence.

You may be stored in preorder the vector, so long as each is determined whether several further behind and next can give hasnext

 

Code:

class BSTIterator {
public:
    BSTIterator(TreeNode* root) {
        idx_ = 0;//数组始
        inOrder(root);
        end_ = vec_.size();//数组终
    }
    
    /** @return the next smallest number */
    int next() {
        return vec_[idx_++];
    }
    
    /** @return whether we have a next smallest number */
    bool hasNext() {
        return idx_ != end_;//注意has只是判断,不能更改idx
    }
private:
    void inOrder(TreeNode* root) {
        if (root != nullptr){
            inOrder(root->left);
            vec_.push_back(root->val);
            inOrder(root->right);
        } 
    }
private:
    std::vector<int> vec_;
    int idx_, end_;
};

 

Answer two:

Recursion allows each stack all the left branch of a tree (that is, the depth of traversal, first encountered the leaf node stops). The current top of the stack is the smallest element, that is, ask the next.

The stack. Enter the point right node. Above operation is repeated until the stack is empty.

Here idea: Only the left leaves continuously stack. Equivalent to manually simulate the recursion stack. A space complexity is lower than answers.

class BSTIterator {
public:
    BSTIterator(TreeNode* root) {
        for (; root != nullptr; root = root->left) {
            sti_.push(root);
        }
    }
    
    /** @return the next smallest number */
    int next() {
        TreeNode* smallest = sti_.top();
        sti_.pop();
        int val = smallest->val;
        smallest = smallest->right;
        for (; smallest != nullptr; smallest = smallest->left) {
            sti_.push(smallest);
        }
        return val;
    }
    
    /** @return whether we have a next smallest number */
    bool hasNext() {
        return !sti_.empty();
    }
private:
    std::stack<TreeNode*> sti_;
};

Guess you like

Origin blog.csdn.net/Mr_zhuo_/article/details/88591776