LeetCode 173 二叉搜索树迭代器
发布日期:2021-05-11 01:24:28 浏览次数:24 分类:精选文章

本文共 984 字,大约阅读时间需要 3 分钟。

  • 分析
    简单题,中序遍历,做这种题重要的是选择什么样的数据结构,对stl中的数据结构要能熟练使用。
  • 代码
/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class BSTIterator {   private:    vector
vec; int ite; void inorder(TreeNode* root){ if(root == nullptr) return; inorder(root -> left); vec.push_back(root -> val); inorder(root -> right); } public: BSTIterator(TreeNode* root): ite(0) { inorder(root); } /** @return the next smallest number */ int next() { return *(vec.begin() + (ite++)); } /** @return whether we have a next smallest number */ bool hasNext() { return vec.begin() + ite < vec.end(); }};/** * Your BSTIterator object will be instantiated and called as such: * BSTIterator* obj = new BSTIterator(root); * int param_1 = obj->next(); * bool param_2 = obj->hasNext(); */
上一篇:LeetCode 779 第K个语法符号
下一篇:LeetCode 129 求根节点到叶节点数字之和

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2025年04月16日 02时39分13秒