forked from mandliya/algorithms_and_data_structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sumTree.cpp
84 lines (79 loc) · 1.79 KB
/
sumTree.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
/**
* Problem: Determine if a tree is sum tree.
* A SumTree is a Binary Tree where the value of a node is equal to sum of the nodes present in its left subtree and right subtree.
* An empty tree is SumTree and sum of an empty tree can be considered as 0.
* A leaf node is also considered as SumTree.
*
* 26
* / \
* 10 3
* / \ \
* 4 6 3
*/
#include <iostream>
struct Node {
/* data */
int data;
Node * left;
Node * right;
Node( int d )
: data{ d }, left{ nullptr }, right{ nullptr } { }
};
/**
* addTree - Adds the contents of the tree
* @param root
* @return total of contents of tree
*/
int addTree( Node * root ) {
if ( root == nullptr ) {
return 0;
}
return (addTree(root->left) + root->data + addTree(root->right)) ;
}
bool sumTree( Node * root )
{
if ( root == nullptr ) {
return true;
}
else if ( root->left == nullptr && root->right == nullptr ) {
return true;
}
else {
if ((addTree(root->left) + addTree(root->right) == root->data) &&
sumTree(root->left) && sumTree(root->right)) {
return true;
} else {
return false;
}
}
}
void inorder(Node * root)
{
if ( root ) {
inorder(root->left);
std::cout << root->data << " ";
inorder(root->right);
}
}
int main()
{
/**
* 26
* / \
* 10 3
* / \ \
* 4 6 3
*/
Node * root = new Node(26);
root->left = new Node(10);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(6);
root->right->right = new Node(3);
std::cout << "Inorder of the tree is :";
inorder(root);
std::cout << std::endl;
std::cout << "Is above tree sum-tree? : ";
std::cout << ( sumTree(root) ? "Yes\n" : "No\n" );
return 0;
}