forked from shruti170901/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDeepest Leaves Sum.cpp
59 lines (52 loc) · 1.34 KB
/
Deepest Leaves Sum.cpp
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
// Using DFS
class Solution
{
public:
unordered_map<int, vector<int>> map;
int height = INT_MIN;
void leaf(TreeNode *root, int level)
{
if (root == nullptr)
return;
map[level].push_back(root->val);
height = max(level, height);
leaf(root->left, level + 1);
leaf(root->right, level + 1);
}
int deepestLeavesSum(TreeNode *root)
{
int sum = 0;
leaf(root, 0);
for (auto it = map[height].begin(); it != map[height].end(); it++)
sum += *it;
return sum;
}
};
/****************************************************************************************/
//Using BFS
class Solution
{
public:
int deepestLeavesSum(TreeNode *root)
{
queue<TreeNode *> q;
int result = 0;
q.push(root);
while (!q.empty())
{
result = 0;
int sz = q.size();
for (int i = 0; i < sz; i++)
{
TreeNode *current = q.front();
q.pop();
result += current->val;
if (current->left)
q.push(current->left);
if (current->right)
q.push(current->right);
}
}
return result;
}
};