[LeetCode] Binary Tree Right Side View 二叉树的右侧视图
2015-04-04 15:06
429 查看
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,
You should return
Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.
这道题要求我们打印出二叉树每一行最右边的一个数字,实际上是求二叉树层序遍历的一种变形,我们只需要保存每一层最右边的数字即可,可以参考我之前的博客 Binary Tree Level Order Traversal 二叉树层序遍历,这道题只要在之前那道题上稍加修改即可得到结果,还是需要用到数据结构队列queue,遍历每层的节点时,把下一层的节点都存入到queue中,每当开始新一层节点的遍历之前,先把新一层最后一个节点值存到结果中,代码如下:
LeetCode All in One 题目讲解汇总(持续更新中...)
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<int> rightSideView(TreeNode *root) { vector<int> res; if (!root) return res; queue<TreeNode*> q; q.push(root); while (!q.empty()) { res.push_back(q.back()->val); int size = q.size(); for (int i = 0; i < size; ++i) { TreeNode *node = q.front(); q.pop(); if (node->left) q.push(node->left); if (node->right) q.push(node->right); } } return res; } };
LeetCode All in One 题目讲解汇总(持续更新中...)
相关文章推荐
- Leetcode 199 Binary Tree Right Side View 二叉树右视图
- Leetcode 199 Binary Tree Right Side View 二叉树右视图
- 【LeetCode-面试算法经典-Java实现】【199-Binary Tree Right Side View(从右边看二叉树)】
- LeetCode 199 Binary Tree Right Side View(二叉树层序遍历)
- 199.leetcode Binary Tree Right Side View(medium)[层次遍历二叉树 队列]
- LeetCode OJ:Binary Tree Right Side View(右侧视角下的二叉树)
- LeetCode—Binary Tree Right Side View 二叉树层序遍历变形,Flatten Binary Tree to Linked List前序遍历变形
- 【LeetCode-面试算法经典-Java实现】【199-Binary Tree Right Side View(从右边看二叉树)】
- Binary Tree Right Side View 二叉树:右视图
- [leetcode] 199 Binary Tree Right Side View
- 【LeetCode】Binary Tree Right Side View 解题报告
- [LeetCode 199] Binary Tree Right Side View
- [Leetcode] Binary Tree Right Side View
- [LeetCode]Binary Tree Right Side View
- [JAVA]LeetCode199 Binary Tree Right Side View
- [leetcode]48 Binary Tree Right Side View
- leetcode 日经贴,Cpp code -Binary Tree Right Side View
- LeetCode "Binary Tree Right Side View"
- leetcode-199 Binary Tree Right Side View
- Leetcode: Binary Tree Right Side View