您的位置:首页 > 其它

Binary Tree Right Side View

2015-10-16 11:17 381 查看
题目:

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]
.
看到这道题就想到了广度优先遍历,使用队列实现
不过中间出现了一个问题,就是怎么该标识每一层的结束,当时想到用二个队列,看了别人的代码后,才发现用size即可。。。

/**
* 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) {
vector<int> ret;
queue<TreeNode*> q;
if(root!=NULL) q.push(root);
while(!q.empty()){
int k=q.size();
for(int i=0;i<k;++i)
{
TreeNode* tmp=q.front();q.pop();
if(i==k-1) ret.push_back(tmp->val);
if(tmp->left!=NULL) q.push(tmp->left);
if(tmp->right!=NULL) q.push(tmp->right);
}
}
return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode