Binary Tree Right Side View
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.
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <—
/ \
2 3 <—
\ \
5 4 <—
解析
树的层次遍历,并将每一层的最后一个节点值加入res。
代码
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
queue<TreeNode*> q;
vector<int> res;
if(!root) return res;
q.push(root);
while(!q.empty()){
int size = q.size();
for(int i=0;i<size;i++){
TreeNode* p = q.front();
q.pop();
if(i==size-1)
res.push_back(p->val);
if(p->left) q.push(p->left);
if(p->right) q.push(p->right);
}
}
return res;
}
};
1125

被折叠的 条评论
为什么被折叠?



