Skip to content

Commit e5a8d8e

Browse files
Added solution
1 parent 79f8633 commit e5a8d8e

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed
+90
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
{
2+
#include <bits/stdc++.h>
3+
using namespace std;
4+
/* A binary tree node has data, pointer to left child
5+
and a pointer to right child */
6+
7+
struct Node
8+
{
9+
int data;
10+
struct Node *left;
11+
struct Node *right;
12+
13+
Node(int x){
14+
data = x;
15+
left = NULL;
16+
right = NULL;
17+
}
18+
};
19+
/* Function to get diameter of a binary tree */
20+
long long treePathsSum(Node *root);
21+
/* Driver program to test size function*/
22+
int main()
23+
{
24+
int t;
25+
scanf("%d
26+
", &t);
27+
while (t--)
28+
{
29+
map<int, Node*> m;
30+
int n;
31+
scanf("%d",&n);
32+
struct Node *root = NULL;
33+
struct Node *child;
34+
while (n--)
35+
{
36+
Node *parent;
37+
char lr;
38+
int n1, n2;
39+
scanf("%d %d %c", &n1, &n2, &lr);
40+
if (m.find(n1) == m.end())
41+
{
42+
parent = new Node(n1);
43+
m[n1] = parent;
44+
if (root == NULL)
45+
root = parent;
46+
}
47+
else
48+
parent = m[n1];
49+
child = new Node(n2);
50+
if (lr == 'L')
51+
parent->left = child;
52+
else
53+
parent->right = child;
54+
m[n2] = child;
55+
}
56+
cout << treePathsSum(root) << endl;
57+
}
58+
return 0;
59+
}
60+
61+
}
62+
/*This is a function problem.You only need to complete the function given below*/
63+
/* Tree node structure used in the program
64+
struct Node
65+
{
66+
int data;
67+
Node* left, *right;
68+
}; */
69+
/*You are required to complete below method */
70+
71+
long long recursiveSum(Node *root, long long currentSum, long long &total){
72+
if(!root->left && !root->right){
73+
total += currentSum*10 + root->data;
74+
return total;
75+
}
76+
if(root->left){
77+
recursiveSum(root->left, currentSum*10 + root->data, total);
78+
}
79+
if(root->right){
80+
recursiveSum(root->right, currentSum*10 + root->data, total);
81+
}
82+
}
83+
84+
long long treePathsSum(Node *root)
85+
{
86+
//Your code here
87+
if(!root) return 0;
88+
long long total = 0, currentSum = 0;
89+
return recursiveSum(root, currentSum, total);
90+
}

0 commit comments

Comments
 (0)