leetcode/src/s0404_sum_of_left_leaves.cpp
2023-01-31 12:22:26 +08:00

28 lines
784 B
C++

#include "s0404_sum_of_left_leaves.hpp"
struct TreeNodeState_S0404 {
TreeNode* ptr;
int sum;
bool isLeft;
};
int S0404::sumOfLeftLeaves(TreeNode* root) {
int sum{0};
queue<TreeNodeState_S0404> q;
if (root) q.push(TreeNodeState_S0404{root, root->val, false});
while (!q.empty()) {
TreeNodeState_S0404 front = q.front();
q.pop();
if (front.ptr->left == nullptr && front.ptr->right == nullptr &&
front.isLeft)
sum += front.ptr->val;
if (front.ptr->left)
q.push(TreeNodeState_S0404{front.ptr->left, front.sum + front.ptr->left->val,
true});
if (front.ptr->right)
q.push(TreeNodeState_S0404{front.ptr->right, front.sum + front.ptr->right->val,
false});
}
return sum;
}