LeetCode | Binary Tree Right Side View
2015-04-06 16:24
225 查看
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.
思路:遍历二叉树,先根结点,再右子树,最后左子树。问题是如何判断某结点的水平右边是否有结点存在,如果存在,那么这个结点就是不要输出的。
方法是,可以设置一个标记层数的level,当level < 结果向量v的个数时,就不要将这个结点放入到结果向量中。
class Solution {
public:
vector<int> rightSideView(TreeNode *root)
{
if(!root)
return v;
else
path(root,0);
return v;
}
void path(TreeNode* root, int level)
{
level++;
if(level > v.size())
v.push_back(root->val);
if(root->right && !root->left)
path(root->right,level);
else if(root->left && !root->right)
path(root->left,level);
else if(root->right && root->left)
{
path(root->right,level);
path(root->left,level);
}
}
private:
vector<int> v;
};
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.
思路:遍历二叉树,先根结点,再右子树,最后左子树。问题是如何判断某结点的水平右边是否有结点存在,如果存在,那么这个结点就是不要输出的。
方法是,可以设置一个标记层数的level,当level < 结果向量v的个数时,就不要将这个结点放入到结果向量中。
class Solution {
public:
vector<int> rightSideView(TreeNode *root)
{
if(!root)
return v;
else
path(root,0);
return v;
}
void path(TreeNode* root, int level)
{
level++;
if(level > v.size())
v.push_back(root->val);
if(root->right && !root->left)
path(root->right,level);
else if(root->left && !root->right)
path(root->left,level);
else if(root->right && root->left)
{
path(root->right,level);
path(root->left,level);
}
}
private:
vector<int> v;
};
相关文章推荐
- 199 Binary Tree Right Side View-LeetCode
- [LeetCode] Binary Tree Right Side View 二叉树的右侧视图
- leetcode 日经贴,Cpp code -Binary Tree Right Side View
- LeetCode "Binary Tree Right Side View"
- Leetcode Binary Tree Right Side View
- leetCode 101/199-Symmetric Tree/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(middle)
- LeetCode OJ Binary Tree Right Side View
- [LeetCode] Binary Tree Right Side View
- LeetCode—Binary Tree Right Side View 二叉树层序遍历变形,Flatten Binary Tree to Linked List前序遍历变形
- LeetCode Binary Tree Right Side View : 思想上的基于队列的广度优先遍历,形式上的一个简单变种
- Leetcode 199 Binary Tree Right Side View
- Binary Tree Right Side View--LeetCode
- [Leetcode] Binary Tree Right Side View
- Leetcode: Binary Tree Right Side View
- [leetcode] Binary Tree Right Side View
- [leetcode]48 Binary Tree Right Side View