0%

sum-of-left-leaves

Sum of Left Leaves – LeetCode 404

Problem

Description

Find the sum of all left leaves in a given binary tree.

Answer

Original

Code

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
26
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(!root) return 0;
if(!root->left) return sumOfLeftLeaves(root->right);
if(!root->right){
if(root->left->left == root->left->right)
return root->left->val;
else
return sumOfLeftLeaves(root->left);
}
if(root->left->left == root->left->right)
return root->left->val + sumOfLeftLeaves(root->right);
else
return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
}
};

思路

简单的用DFS查找左子叶而后返回加和。用BFS并不占优。时间复杂度$O(n)$,空间复杂度$O(n)$。
耗时$4$ ms,排名$58.70\%$

Better

思路

重写了代码,减少了不必要的分支。时间复杂度$O(n)$,空间复杂度$O(n)$。
耗时$4$ ms,排名$58.70\%$

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
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);
}
};