国产探花免费观看_亚洲丰满少妇自慰呻吟_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(); */


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 林州市| 常山县| 夏河县| 旺苍县| 全椒县| 铁力市| 博罗县| 视频| 永定县| 安岳县| 枝江市| 明溪县| 塘沽区| 驻马店市| 金昌市| 兴安县| 东方市| 霞浦县| 宜君县| 黄大仙区| 朝阳市| 从江县| 肥东县| 保定市| 磐安县| 合阳县| 马关县| 集安市| 晋州市| 丹寨县| 社旗县| 友谊县| 怀集县| 民县| 通州市| 许昌市| 伊宁市| 辽宁省| 闽清县| 灵山县| 南平市|