Skip to content

Commit 6d26c99

Browse files
committed
Transform Binary tree to Sum tree
1 parent 1c79409 commit 6d26c99

File tree

2 files changed

+96
-0
lines changed

2 files changed

+96
-0
lines changed

Tree/TransfromToSumTree.cpp

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
#include <iostream>
2+
#include <vector>
3+
using namespace std;
4+
5+
// Node class
6+
class Node
7+
{
8+
public:
9+
int data;
10+
Node *left;
11+
Node *right;
12+
13+
Node(int val)
14+
{
15+
data = val;
16+
left = right = NULL;
17+
}
18+
};
19+
20+
static int idx = -1;
21+
Node *buildTree(vector<int> preorder)
22+
{
23+
idx++;
24+
25+
// base case
26+
if (preorder[idx] == -1)
27+
{
28+
return NULL;
29+
}
30+
31+
// create root node
32+
Node *root = new Node(preorder[idx]);
33+
34+
// left sub tree recursion call
35+
root->left = buildTree(preorder);
36+
37+
// right sub tree recursion call
38+
root->right = buildTree(preorder);
39+
40+
return root;
41+
}
42+
43+
void preOrder(Node *root)
44+
{
45+
// base case
46+
if (root == NULL)
47+
{
48+
return;
49+
}
50+
51+
cout << root->data << " ";
52+
53+
// left sub tree recursion call
54+
preOrder(root->left);
55+
56+
// right sub tree recursion call
57+
preOrder(root->right);
58+
}
59+
60+
// transform to Sum tree
61+
int sumTree(Node *root)
62+
{
63+
// base case
64+
if (root == NULL)
65+
{
66+
return 0;
67+
}
68+
69+
// left sub tree call
70+
int leftSum = sumTree(root->left);
71+
72+
// right subtree call
73+
int rightSum = sumTree(root->right);
74+
75+
root->data += leftSum + rightSum;
76+
77+
return root->data;
78+
}
79+
80+
int main()
81+
{
82+
vector<int> preorder = {1, 2, -1, -1, 3, 4, -1, -1, 5, -1, -1};
83+
Node *root = buildTree(preorder);
84+
85+
cout << "before conversion: ";
86+
preOrder(root);
87+
cout << endl;
88+
89+
sumTree(root);
90+
91+
cout << "after conversion: ";
92+
preOrder(root);
93+
cout << endl;
94+
95+
return 0;
96+
}

Tree/TransfromToSumTree.exe

67.3 KB
Binary file not shown.

0 commit comments

Comments
 (0)