Leetcode NO.199 Binary Tree Right Side View
2015-05-08 04:43
316 查看
本题题目要求如下:
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,我感觉现在我dfs用的还算是比较熟练了。。。
我的思路未必是最简的,毕竟挺耗空间的。。但是时间复杂度还是不错的。。
思路如下:
常规的DFS,只不过在DFS上面加入了层数,比如1在第一层,2,3在第二层。。。都存在二维数组中,第一维是level
这样跑DFS,recursive中,优先搜索左边的node,这样会保证同一层的访问顺序必然是从左到右。。。
然后把每层对应数组的最后一个数提取出来,就可以返回答案
代码如下:
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].
本题题目要是很简单的,其实就是dfs,我感觉现在我dfs用的还算是比较熟练了。。。
我的思路未必是最简的,毕竟挺耗空间的。。但是时间复杂度还是不错的。。
思路如下:
常规的DFS,只不过在DFS上面加入了层数,比如1在第一层,2,3在第二层。。。都存在二维数组中,第一维是level
这样跑DFS,recursive中,优先搜索左边的node,这样会保证同一层的访问顺序必然是从左到右。。。
然后把每层对应数组的最后一个数提取出来,就可以返回答案
代码如下:
/** * 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: vector<int> rightSideView(TreeNode* root) { dfs(root, 0); vector<int> ret; for (int i = 0; i < res.size(); ++i) { ret.push_back(res[i].back()); } return ret; } private: vector<vector<int>> res; void dfs(TreeNode* root, int level) { if (root == NULL) return; if (level == res.size()) { vector<int> tmp; res.push_back(tmp); } res[level].push_back(root->val); dfs(root->left, level+1); dfs(root->right, level+1); } };
相关文章推荐
- LeetCode No.199 Binary Tree Right Side View
- leetCode No.199 Binary Tree Right Side View
- leetCode 101/199-Symmetric Tree/Binary Tree Right Side View
- LeetCode(199) Binary Tree Right Side View解题报告
- 【Leetcode】Binary Tree Right Side View
- [LeetCode]Binary Tree Right Side View
- leetcode -- Binary Tree Right Side View -- 重点
- Leetcode: Binary Tree Right Side View
- leetcode-Binary Tree Right Side View
- 【LeetCode-面试算法经典-Java实现】【199-Binary Tree Right Side View(从右边看二叉树)】
- Leetcode | Binary Tree Right Side View
- leetcode_c++:树: Binary Tree Right Side View(199)
- Leetcode 199 Binary Tree Right Side View 二叉树右视图
- LeetCode 199-Binary Tree Right Side View
- leetcode 日经贴,Cpp code -Binary Tree Right Side View
- [leetcode-199]Binary Tree Right Side View(java)
- Leetcode 199: Binary Tree Right Side View
- LeetCode #199 - Binary Tree Right Side View
- Leetcode: Binary Tree Right Side View (Java)
- LeetCode: Binary Tree Right Side View