-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1302. Deepest Leaves Sum.cpp
123 lines (85 loc) · 2.77 KB
/
1302. 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#include<vector>
#include<iostream>
using namespace std;
// 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 deepestLeavesSum(TreeNode* root) {
// We need to find out the depth of the tree first
// so we only consider those leaf nodes
calculateDepthOfTree(root,0);
// Recursive DFS func to calculate
// sum
traverseTree(root,0);
return sum;
}
private:
void calculateDepthOfTree(TreeNode* node,int currentDepth){
// check if this is a leaf node
if(node->left == nullptr && node->right == nullptr){
// We mark this as depth of tree, only if it's greater
// than older depth
depth = max(depth,currentDepth);
return;
}
// continue dfs on left and right nodes
// (if they exist)
if(node->left){
calculateDepthOfTree(node->left,currentDepth+1);
}
if(node->right){
calculateDepthOfTree(node->right,currentDepth+1);
}
}
// Recurisve DFS func to calculate sum of deepest leaves
void traverseTree(TreeNode* node,int currentDepth){
// only append sum if
// 1) this is a leaf node
// 2) the current depth == total depth of tree ( we
// calculated this in calculateDepthOfTree func )
if(node->left == nullptr && node->right == nullptr && currentDepth == depth){
sum += node->val;
return;
}
// continue dfs on left and right nodes
// (if they exist)
if(node->left){
traverseTree(node->left,currentDepth+1);
}
if(node->right){
traverseTree(node->right,currentDepth+1);
}
}
int sum = 0;
int depth = 0;
};
// [1,2,3,4,5,null,6,7,null,null,null,null,8]
int main(){
Solution solution;
TreeNode* root = new TreeNode(1);
TreeNode* n2 = new TreeNode(2);
TreeNode* n3 = new TreeNode(3);
TreeNode* n4 = new TreeNode(4);
TreeNode* n5 = new TreeNode(5);
TreeNode* n6 = new TreeNode(6);
TreeNode* n7 = new TreeNode(7);
TreeNode* n8 = new TreeNode(8);
root->left = n2;
root->right = n3;
n2->left = n4;
n2->right = n5;
n4->left = n7;
n3->right = n6;
n6->right = n8;
int answer = solution.deepestLeavesSum(root);
cout << "Answer is: " << answer << endl;
return 0;
}