LeetCode 404 왼쪽 잎의 합계
주어진 이진 트리의 모든 왼쪽 잎의 합을 계산합니다.
예:
3
/ \
9 20
/ \
15 7
이 이진 트리에는 두 개의 왼쪽 잎, 9와 15가 있으므로 24가 반환됩니다.
이진 트리에서 BFS를 수행합니다. 노드의 왼쪽 자식 노드가 리프 노드 인 경우 응답에 추가합니다. AC 코드는 다음과 같습니다.
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
int ans=0;
queue<TreeNode*>q;
q.push(root);
while(!q.empty()){
TreeNode* t=q.front();
q.pop();
if(t){
if(t->left){
q.push(t->left);
if(t->left->left==NULL&&t->left->right==NULL) ans+=t->left->val;
}
if(t->right) q.push(t->right);
}
}
return ans;
}
};