LC 173. Binary Search Tree Iterator

题目描述

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.

Example:

BSTIterator iterator = new BSTIterator(root);
iterator.next();    // return 3
iterator.next();    // return 7
iterator.hasNext(); // return true
iterator.next();    // return 9
iterator.hasNext(); // return true
iterator.next();    // return 15
iterator.hasNext(); // return true
iterator.next();    // return 20
iterator.hasNext(); // return false

参考答案

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

答案解析

建立一个新的stack,其中存储包括自身的左孩子,这意味着整条树都存在里面,而最上边的永远是树的最左孩子。

next函数,就是把最上面的弹出来,将该点的右孩子(以及它的所有左孩子)给存了,从而保证最小的在第一个。

posted @ 2019-10-09 18:57  schaffen  阅读(152)  评论(0编辑  收藏  举报