-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday_08.cpp
More file actions
44 lines (38 loc) · 1.12 KB
/
day_08.cpp
File metadata and controls
44 lines (38 loc) · 1.12 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
/*PROBLEM STATEMENT:
For all leaves in the tree, consider the numbers represented by the path from the root to that leaf.
Return the sum of these numbers.
Example 1:
1
/ \
0 1
/ \ / \
0 1 0 1
Input: [1,0,1,0,1,0,1]
Output: 22
Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
*/
//CODE:
/*
* 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 {
int sumRootToLeaf(TreeNode* root,int sum){
if(!root) return 0;
sum = (sum << 1) + root->val;
//checks if the node is leaf or not
if(!root->left && !root->right) return sum;
return sumRootToLeaf(root->left, sum) + sumRootToLeaf(root->right, sum);
}
public:
int sumRootToLeaf(TreeNode* root) {
return sumRootToLeaf(root,0);
}
};