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

173 Binary Search Tree Iterator 二叉搜索树迭代器

时间:2018-04-07 16:07:42      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:实现   iterator   nod   pre   str   迭代器   blog   etc   esc   

实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。
调用 next() 将返回二叉搜索树中的下一个最小的数。
注意: next() 和hasNext() 操作的时间复杂度是O(1),并使用 O(h) 内存,其中 h 是树的高度。

详见:https://leetcode.com/problems/binary-search-tree-iterator/description/

/**
 * 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)
        {
            stk.push(root);
            root=root->left;
        }
    }

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

    /** @return the next smallest number */
    int next() {
        TreeNode *node=stk.top();
        stk.pop();
        int res=node->val;
        if(node->right)
        {
            node=node->right;
            while(node)
            {
                stk.push(node);
                node=node->left;
            }
        }
        return res;
    }
private:
    stack<TreeNode*> stk;
};

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

 参考:https://www.cnblogs.com/grandyang/p/4231455.html

173 Binary Search Tree Iterator 二叉搜索树迭代器

标签:实现   iterator   nod   pre   str   迭代器   blog   etc   esc   

原文地址:https://www.cnblogs.com/xidian2014/p/8733319.html

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