国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Leetcode 173 Binary Search Tree Iterator

2019-11-08 03:09:24
字體:
來源:轉載
供稿:網友

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(); */


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 玛曲县| 军事| 库尔勒市| 自治县| 洪洞县| 苍南县| 岳西县| 车致| 邵阳市| 嘉峪关市| 淳安县| 鸡东县| 阿克苏市| 乌鲁木齐县| 沈阳市| 锡林郭勒盟| 宁明县| 东至县| 馆陶县| 武陟县| 廊坊市| 闵行区| 佳木斯市| 白朗县| 闽清县| 金溪县| 永兴县| 盐边县| 正宁县| 苏州市| 嘉兴市| 彩票| 全州县| 古交市| 特克斯县| 南通市| 上栗县| 夏津县| 日照市| 宜城市| 广东省|