# Binary Tree Right Side View

1. 问题

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].

2. 解答
class Solution1 {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> res;

while(root)
{
res.push_back(root->val);
TreeNode *f1;

if(root->right==NULL)
{
f1=root->left;
if(f1==NULL) break;
}
else
f1=root->right;

root=f1;
}

return res;
}
};

class Solution {
public:
vector<int> rightSideView(TreeNode *root) {
vector<int> ans;
if (root == nullptr) return ans;
queue<TreeNode*> que;
que.push(root);
TreeNode* curr;
while(!que.empty()) {
int cnt = que.size();
for (int i = 0; i < cnt; i++) {
curr = que.front(); que.pop();
if (curr->left) {
que.push(curr->left);
}
if (curr->right) {
que.push(curr->right);
}
}
ans.push_back(curr->val);
}
return ans;
}
};

• 本文已收录于以下专栏：

举报原因： 您举报文章：Binary Tree Right Side View 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)