forked from larissalages/code_problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1302.cpp
More file actions
58 lines (42 loc) · 1.63 KB
/
1302.cpp
File metadata and controls
58 lines (42 loc) · 1.63 KB
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
/**
* Problem link: https://leetcode.com/problems/deepest-leaves-sum/
* Solution:
* (1) If the current leaf node depth is greater than the maximum leaf depth found till now, set maximum depth as current leaf depth and initialize sum.
* (2) If the current leaf node depth is less than the maximum leaf depth found till now, dont do anything.
* (3) If the current leaf node depth is equal to the maximum leaf depth found till now, increase the sum.
*
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int mx_d, ans;
void dfs(TreeNode *node, int depth) {
if (node == NULL) return;
if (node->right == NULL && node->left == NULL) {
if (depth == mx_d) {
ans += node->val;
} else if (depth > mx_d) {
mx_d = depth;
ans = node->val;
} else if (depth < mx_d) {
return;
}
}
if (node->right != NULL) dfs(node->right, depth+1);
if (node->left != NULL) dfs(node->left, depth+1);
}
int deepestLeavesSum(TreeNode* root) {
mx_d = 0;
ans = 0;
dfs(root, 0);
return ans;
}
};