[LeetCode] 173. Binary Search Tree Iterator

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.
Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.

解析

非递归的中序遍历。需要一个栈,一开始先存储到最左叶子节点的路径。在遍历的过程中,只要当前节点存在右孩子,则进入右孩子,存除从此处开始到当前子树里最左叶子节点的路径。

代码

class BSTIterator {
public:
    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() {
        TreeNode* node = s.top();
        s.pop();
        int res = node->val;
        if(node->right){
            node = node->right;
            while(node){
                s.push(node);
                node = node->left;
            }
        }
        return res;
    }

private:
    stack<TreeNode*> s;
};

参考

https://blog.csdn.net/whuwangyi/article/details/42304407
http://www.cnblogs.com/grandyang/p/4231455.html

猜你喜欢

转载自blog.csdn.net/Peng_maple/article/details/82453867
今日推荐