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

C++实现LeetCode(199.二叉树的右侧视图)

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

这篇文章主要介绍了C++实现LeetCode(199.二叉树的右侧视图),本篇文章通过简要的案例,讲解

来源gao!daima.com搞$代!码网

了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下

[LeetCode] 199.Binary Tree Right Side View 二叉树的右侧视图

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

For example:
Given the following binary tree,

   1            <—
/   \
2     3         <—
\     \
5     4       <—

You should return [1, 3, 4].

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

这道题要求我们打印出二叉树每一行最右边的一个数字,实际上是求二叉树层序遍历的一种变形,我们只需要保存每一层最右边的数字即可,可以参考我之前的博客 Binary Tree Level Order Traversal 二叉树层序遍历,这道题只要在之前那道题上稍加修改即可得到结果,还是需要用到数据结构队列queue,遍历每层的节点时,把下一层的节点都存入到queue中,每当开始新一层节点的遍历之前,先把新一层最后一个节点值存到结果中,代码如下:

 /** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector rightSideView(TreeNode *root) { vector res; if (!root) return res; queue q; q.push(root); while (!q.empty()) { res.push_back(q.back()->val); int size = q.size(); for (int i = 0; i left) q.push(node->left); if (node->right) q.push(node->right); } } return res; } };

以上就是C++实现LeetCode(199.二叉树的右侧视图)的详细内容,更多请关注gaodaima搞代码网其它相关文章!


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

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

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

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

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