LeetCode#404 | Nobilta's Blog
0%

LeetCode#404

LeetCode#404左叶子子之和

题目链接
深搜遍历每个节点,判断一下是否为左叶子节点即可,没啥好说的,我是用一个标记flag来记录是否为左节点的,如果不是则直接继续遍历
附代码:

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
/**
* 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:
void dfs(TreeNode* node,long long &ans,int flag)
{
if(flag == 1)
{
if(node -> left == nullptr && node -> right == nullptr)
{
ans+=node -> val;
return;
}
if(node -> left != nullptr)
dfs(node->left,ans,1);
if(node -> right != nullptr)
dfs(node->right,ans,0);
}
else
{
if(node -> left != nullptr)
dfs(node->left,ans,1);
if(node -> right != nullptr)
dfs(node->right,ans,0);
}
}
int sumOfLeftLeaves(TreeNode* root) {
long long ans = 0;
if(root == nullptr)
return 0;
dfs(root,ans,0);
return ans;
}
};
您的支持将鼓励我继续创作!