-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path404. Sum of Left Leaves
98 lines (89 loc) · 2.39 KB
/
404. Sum of Left Leaves
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// 3 ms
/**
* 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->right) && left) return root->val;
int sum = 0;
left = 1; sum += sumOfLeftLeaves(root->left);
left = 0; sum += sumOfLeftLeaves(root->right);
return sum;
}
private:
int left = 0; // left is 1, right is 0;
};
// 3 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);
}
};
// 这个是不正确的解法,错误在于:当左孩子没有左右孙子,左孩子称为左叶节点。所以说,不到最后一个不是叶子,是树杈……没学过数据结构真是orz
// 还有当二叉树为[1]时,应返回0,没有左叶节点
/**
* 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;
int sum = 0;
if (left)
{
if (!(root->left || root->right))
{
return root->val;
}
if (root->left)
{
left = 1;
sum += sumOfLeftLeaves(root->left);
}
if (root->right)
{
left = 0;
sum += sumOfLeftLeaves(root->right);
}
return root->val + sum;
}
else
{
if (!(root->left || root->right))
{
return 0;
}
if (root->left)
{
left = 1;
sum += sumOfLeftLeaves(root->left);
}
if (root->right)
{
left = 0;
sum += sumOfLeftLeaves(root->right);
}
return sum;
}
}
private:
int left = 0; // left is 1, right is 0
};