您的位置:首页 > 其它

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,

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;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode 二叉树