Binary Tree Right Side View
2016-01-28 10:43
218 查看
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
思路:dfs。每次优先遍历右子树。同时需要记录当前所处的深度,当第一次进入一个深度时,就将该值存入结果。因为我们每次都是优先遍历右子树,因此这样做一定是最右侧能看到的节点。
For example:
Given the following binary tree,
1 <--- / \ 2 3 <--- \ \ 5 4 <---
You should return
[1, 3, 4].
思路:dfs。每次优先遍历右子树。同时需要记录当前所处的深度,当第一次进入一个深度时,就将该值存入结果。因为我们每次都是优先遍历右子树,因此这样做一定是最右侧能看到的节点。
class Solution { public: void help(vector<int>& res, TreeNode* root, int depth) { if (!root) return; if (res.size() < depth + 1) res.push_back(root->val); help(res, root->right, depth + 1); help(res, root->left, depth + 1); } vector<int> rightSideView(TreeNode* root) { vector<int> res; help(res, root, 0); return res; } };
相关文章推荐
- Webview之H5页面调用android的图库及文件管理
- js基础用法全集
- ldconfig命令
- linux下tcp socket的SO_REUSEPORT和SO_REUSEADDR
- android:clipToPadding的使用
- Java设计模式之单例模式
- RecyclerView 列表控件中简单实现时间线
- Webview之H5页面调用android的图库及文件管理
- coursera课程Text Retrieval and Search Engines之Week 3 Overview
- 去掉字符串中的空格 JS JQ 正则三种不同写法
- Java多线程实现的2个方式
- opencv2.4.8+vs2012环境搭建
- HDU 1297:Children’s Queue
- mongodb备份还原
- java类库中的System.arraycopy()方法
- centos6.5mimi版 网卡驱动激活
- 避免使用GroupByKey
- Windows下利用CMake和VS2013编译OpenCV
- 如何创建Lucene索引
- android 获取屏幕宽高