Binary Tree Right Side View
2015-10-06 18:32
579 查看
原题
思路
code
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].
思路
可用bfs来求解, 关键在于利用标记信息来区分树中的每一层, 然后把每一层最后一个节点的值添加到结果队列中即可.
code
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: // void rightSideView(const TreeNode* root, vector<int>& res) { // if(root == NULL) return ; // res.push_back(root->val); // if(root->right) // rightSideView(root->right, res); // else // rightSideView(root->left, res); // } vector<int> rightSideView(TreeNode* root) { /// error // vector<int> res; // rightSideView(root, res); // return res; vector<int> res; if(root == NULL) return res; int val; queue<TreeNode*> q; // null is a sign variable TreeNode* null = NULL; q.push(root); q.push(null); // bfs的关键在于找到标记信息(标记每一层) // bfs中的标记信息为NULL // 每次遇到NULL, 则更新res // 值得注意的时, 每次遇到标志信息时, // 需要检查当前队列是否为空, // 否则会导致死循环 while(!q.empty()) { TreeNode* r = q.front(); q.pop(); if(r == null) { // if q is empty, stop pushing null if(!q.empty()) { q.push(null); } res.push_back(val); } else { val = r->val; if(r->left) q.push(r->left); if(r->right) q.push(r->right); } } return res; } };
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性
- C++ Custom Control控件向父窗体发送对应的消息