[LeetCode] Binary Tree Right Side View
2015-07-11 18:12
295 查看
A simple application of level-order traversal. Just push the last node in each level into the result.
The code is as follows.
Well, the above code is of BFS. This problem can still be solved using DFS. The code is as follows. Play with it to see how it works :-)
The code is as follows.
class Solution { public: vector<int> rightSideView(TreeNode* root) { vector<int> right; if (!root) return right; queue<TreeNode*> toVisit; toVisit.push(root); while (!toVisit.empty()) { TreeNode* rightNode = toVisit.back(); right.push_back(rightNode -> val); int num = toVisit.size(); for (int i = 0; i < num; i++) { TreeNode* node = toVisit.front(); toVisit.pop(); if (node -> left) toVisit.push(node -> left); if (node -> right) toVisit.push(node -> right); } } return right; } };
Well, the above code is of BFS. This problem can still be solved using DFS. The code is as follows. Play with it to see how it works :-)
class Solution { public: vector<int> rightSideView(TreeNode* root) { vector<int> right; if (!root) return right; rightView(root, right, 0); } private: void rightView(TreeNode* node, vector<int>& right, int level) { if (!node) return; if (level == right.size()) right.push_back(node -> val); rightView(node -> right, right, level + 1); rightView(node -> left, right, level + 1); } };
相关文章推荐
- C语言 交换两个变量的值的实现
- 南阳oj 题目198 数数
- C++笔记(5):指针
- android中线程的同步
- 自定义Team Foundation Server (TFS) 与Project Professional的集成字段
- php实现源代码加密的方法
- springmvc+mybatis登录功能
- kaggle-电影评分预测从零开始
- 1.写一个Mvc框架_超轻量级MVC框架的设计和实现
- 在PL/SQL使用游标获取数据及动态SQL
- LeetCode 之 Implement Queue using Stacks — C++ 实现
- chapter17test5
- 分布式ElasticSearch简介
- Oracle-BPM(六)
- 在头文件中添加文件注释
- java学习之旅56--数组_StringBuilder和StringBuffer的使用_常用方法_方法链的实现_JDK源码分析
- Working with the Path Class
- 大数阶乘的位数和精确值计算【转】
- java开发必备的工具
- 汇编学习([BX]和loop指令)