Solution: Recursion
Time complexity: O(n)
Space complexity: O(h)
C++
1 2 3 4 5 6 7 8 9 10 11 |
// Author: Huahua // Running time: 4 ms class Solution { public: int sumOfLeftLeaves(TreeNode* root) { if (!root) return 0; if (root->left && !root->left->left && !root->left->right) return root->left->val + sumOfLeftLeaves(root->right); return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right); } }; |
Iterative
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// Author: Huahua // Running time: 4 ms class Solution { public: int sumOfLeftLeaves(TreeNode* root) { if (!root) return 0; queue<TreeNode*> q; q.push(root); int sum = 0; while (!q.empty()) { TreeNode* n = q.front(); q.pop(); TreeNode* l = n->left; if (l) { if (!l->left && !l->right) sum += l->val; else q.push(l); } if (n->right) q.push(n->right); } return sum; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment