-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtreetosum.cpp
66 lines (56 loc) · 1.46 KB
/
treetosum.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
#include<stdio.h>
/* A tree node structure */
struct node
{
int data;
struct node *left;
struct node *right;
};
// Convert a given tree to a tree where every node contains sum of values of
// nodes in left and right subtrees in the original tree
int toSumTree(struct node *node)
{
if(node == NULL)
return 0;
int x = node->data;
node->data = toSumTree(node->right) + toSumTree(node->left);
return node->data + x;
}
// A utility function to print inorder traversal of a Binary Tree
void printInorder(struct node* node)
{
if (node == NULL)
return;
printInorder(node->left);
printf("%d ", node->data);
printInorder(node->right);
}
/* Utility function to create a new Binary Tree node */
struct node* newNode(int data)
{
struct node *temp = new struct node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
/* Driver function to test above functions */
int main()
{
struct node *root = NULL;
int x;
/* Constructing tree given in the above figure */
root = newNode(10);
root->left = newNode(-2);
root->right = newNode(6);
root->left->left = newNode(8);
root->left->right = newNode(-4);
root->right->left = newNode(7);
root->right->right = newNode(5);
toSumTree(root);
// Print inorder traversal of the converted tree to test result of toSumTree()
printf("Inorder Traversal of the resultant tree is: \n");
printInorder(root);
printf("\n");
return 0;
}