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

Binary Search Tree Iterator -- leetcode

时间:2015-06-26 18:11:51      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:leetcode   二叉搜索树   迭代   中序遍历   

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.


基本思路:

其实就是中序遍历的非递实现。


这next smallest意思就是,从小到大逐个返回。 第一次看到,竟然理解反了。还以为是从大到小逐个返回。


/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
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() {
        auto root = s_.top();
        s_.pop();
        auto ans = root->val;
        root = root->right;
        while (root) {
            s_.push(root);
            root = root->left;
        }
        return ans;
    }

private:
    stack<TreeNode *> s_;
};

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


Binary Search Tree Iterator -- leetcode

标签:leetcode   二叉搜索树   迭代   中序遍历   

原文地址:http://blog.csdn.net/elton_xiao/article/details/46651341

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