[LeetCode] 199. Binary Tree Right Side View
阿新 • • 發佈:2018-11-09
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;
}
};