码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode[Tree]: Binary Search Tree Iterator

时间:2015-03-03 01:12:50      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:leetcode   tree   stack   bst   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.

参考:https://oj.leetcode.com/discuss/20001/my-solutions-in-3-languages-with-stack

解题思路:用一个stack保存从根节点开始的所有左孩子,每次调用next()就从stack里面pop一个元素,并将以这个节点的右孩子为根节点的子树重复同样的过程。

这个算法满足O(h)的空间复杂度,hasNext()的时间复杂度满足O(1),尽管next()的时间复杂度为O(h),但是这个算法的处理过程仍然值得学习。

C++代码实现如下:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
private:
    stack<TreeNode *> nodeStack;

    void pushAll(TreeNode *root) {
        for (TreeNode *node = root; node != nullptr; node = node->left) {
            nodeStack.push(node);
        }
    }

public:
    BSTIterator(TreeNode *root) {
        pushAll(root);
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
        return !nodeStack.empty();
    }

    /** @return the next smallest number */
    int next() {
        TreeNode *node = nodeStack.top();
        nodeStack.pop();
        pushAll(node->right);
        return node->val;
    }
};

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = BSTIterator(root);
 * while (i.hasNext()) cout << i.next();
 */

该算法的时间性能表现如下:

技术分享

LeetCode[Tree]: Binary Search Tree Iterator

标签:leetcode   tree   stack   bst   iterator   

原文地址:http://blog.csdn.net/chfe007/article/details/44027503

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!