• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

C++实现LeetCode(173.二叉搜索树迭代器)

c++ 搞代码 4年前 (2022-01-06) 29次浏览 已收录 0个评论
文章目录[隐藏]

这篇文章主要介绍了C++实现LeetCode(173.二叉搜索树迭代器),本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下

[LeetCode] 173.Binary Search Tree Iterator 二叉搜索树迭代器

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

Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

这道题主要就是考二叉树的中序遍历的非递归形式,需要额外定义一个栈来辅助,二叉搜索树的建树规则就是左<根<右,用中序遍历即可从小到大取出所有节点。代码如下:

 /** * 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) { s.push(root); root = root->left; } } /** @return whether we have a next smalle<strong style="color:transparent">来源gaodai#ma#com搞@@代~&码网</strong>st number */ bool hasNext() { return !s.empty(); } /** @return the next smallest number */ int next() { TreeNode *n = s.top(); s.pop(); int res = n->val; if (n->right) { n = n->right; while (n) { s.push(n); n = n->left; } } return res; } private: stack s; }; /** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */

以上就是C++实现LeetCode(173.二叉搜索树迭代器)的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:C++实现LeetCode(173.二叉搜索树迭代器)
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址