Skip to content

Commit 8f794b9

Browse files
authored
Add solution for deepest leaves sum leetcode problem
1 parent b20f798 commit 8f794b9

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

leetcode/cpp/Tree/1302.cpp

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/**
2+
* Problem link: https://leetcode.com/problems/deepest-leaves-sum/
3+
* Solution:
4+
* (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.
5+
* (2) If the current leaf node depth is less than the maximum leaf depth found till now, dont do anything.
6+
* (3) If the current leaf node depth is equal to the maximum leaf depth found till now, increase the sum.
7+
*
8+
* Definition for a binary tree node.
9+
* struct TreeNode {
10+
* int val;
11+
* TreeNode *left;
12+
* TreeNode *right;
13+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
14+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
15+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
16+
* };
17+
*/
18+
class Solution {
19+
public:
20+
21+
int mx_d, ans;
22+
23+
void dfs(TreeNode *node, int depth) {
24+
25+
if (node == NULL) return;
26+
27+
if (node->right == NULL && node->left == NULL) {
28+
29+
if (depth == mx_d) {
30+
31+
ans += node->val;
32+
33+
} else if (depth > mx_d) {
34+
35+
mx_d = depth;
36+
ans = node->val;
37+
38+
} else if (depth < mx_d) {
39+
40+
return;
41+
}
42+
}
43+
44+
if (node->right != NULL) dfs(node->right, depth+1);
45+
46+
if (node->left != NULL) dfs(node->left, depth+1);
47+
}
48+
49+
int deepestLeavesSum(TreeNode* root) {
50+
51+
mx_d = 0;
52+
ans = 0;
53+
54+
dfs(root, 0);
55+
56+
return ans;
57+
}
58+
};

0 commit comments

Comments
 (0)