Deepest Leaves Sum LeetCode solution in C++

1
**#Vote if u like ❤️**
2

3
class Solution {
4
public:
5
void fun(TreeNode *root, int l, map<int, vector<int>> &m) {
6
if (root == NULL) return; // If root is NULL it will return
7
m[l].push_back(root->val); // With level as key inserting the value to the vector
8
fun(root->left, l + 1, m); // passing the left with level + 1
9
fun(root->right, l + 1, m); // passing right with level + 1
10
}
11
int deepestLeavesSum(TreeNode *root) {
12
map<int, vector<int>> m; // Map with key as level and value of vector for storing the values
13
fun(root, 0, m); // A void fun with map and level as 0
14
auto itr = m.rbegin(); // Hence we need the leaves node the nodes are
15
// present in last level
16
int sum = 0; // Sum Variable
17
for (int i = 0; i < itr->second.size(); i++) {
18
sum += itr->second[i];
19
}
20
return sum;
21
}
22
};
23

24
-Yash:)

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0