404. Sum of Left Leaves - cocoder39/coco39_LC GitHub Wiki
time is O(n), space is O(w) where w is width of the tree
int sumOfLeftLeaves(TreeNode* root) {
int res = 0;
if (! root) return res;
queue<TreeNode*> q;
q.push(root);
while (! q.empty()) {
int sz = q.size();
for (int i = 0; i < sz; i++) {
TreeNode* node = q.front();
q.pop();
if (node->left) {
if (isLeave(node->left)) {
res += node->left->val;
} else { //unnecessary to push a leave into queue
q.push(node->left);
}
}
if (node->right) {
if (! isLeave(node->right)) {
q.push(node->right);
}
}
}
}
return res;
}
time is O(n) and space for call stack is O(h) where h is height of tree
int sumOfLeftLeaves(TreeNode* root) {
if (! root) {
return 0;
} else if (root->left && ! root->left->left && ! root->left->right) {
return root->left->val + sumOfLeftLeaves(root->right);
} else {
return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
}
}