首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 173 Binary Search Tree Iterator

Leetcode 173 Binary Search Tree Iterator

作者头像
triplebee
发布2018-01-12 14:48:45
5230
发布2018-01-12 14:48:45
举报

mplement 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.

设计题,实现一个二叉搜索树迭代类,要求实现next()和hasNext()两个成员函数

很容易想到中序遍历,因为需要在O(1)复杂度完成,所以不能使用在线的方式,在构造函数中先使用中序遍历构建出序列。

两个方法以离线的方式查询就可以了。

过完年要好好加油了

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
public:
    queue<int> q;
    void dfs(TreeNode *root)
    {
        if(!root) return ;
        if(root->left) dfs(root->left);
        q.push(root->val);
        if(root->right) dfs(root->right);
    }
    BSTIterator(TreeNode *root) 
    {
        dfs(root);
    }
    /** @return whether we have a next smallest number */
    bool hasNext() 
    {
        if(q.empty()) return false;
        return true;
    }
    /** @return the next smallest number */
    int next() 
    {
        int res = q.front();
        q.pop();
        return res;
    }
};

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = BSTIterator(root);
 * while (i.hasNext()) cout << i.next();
 */
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-02-17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档