forked from anish2210/hacktober2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinarytree.cpp
87 lines (74 loc) · 1.65 KB
/
binarytree.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
85
86
87
// C++ program to check if Binary tree
// is sum tree or not
#include <iostream>
using namespace std;
// A binary tree node has data,
// left child and right child
struct node
{
int data;
struct node* left;
struct node* right;
};
// A utility function to get the sum
// of values in tree with root as root
int sum(struct node *root)
{
if (root == NULL)
return 0;
return sum(root->left) + root->data +
sum(root->right);
}
// Returns 1 if sum property holds for
// the given node and both of its children
int isSumTree(struct node* node)
{
int ls, rs;
// If node is NULL or it's a leaf
// node then return true
if (node == NULL ||
(node->left == NULL &&
node->right == NULL))
return 1;
// Get sum of nodes in left and
// right subtrees
ls = sum(node->left);
rs = sum(node->right);
// If the node and both of its
// children satisfy the property
// return 1 else 0
if ((node->data == ls + rs) &&
isSumTree(node->left) &&
isSumTree(node->right))
return 1;
return 0;
}
// Helper function that allocates a new node
// with the given data and NULL left and right
// pointers.
struct node* newNode(int data)
{
struct node* node = (struct node*)malloc(
sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
// Driver code
int main()
{
struct node *root = newNode(26);
root->left = newNode(10);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(6);
root->right->right = newNode(3);
if (isSumTree(root))
cout << "The given tree is a SumTree ";
else
cout << "The given tree is not a SumTree ";
getchar();
return 0;
}
// This code is contributed by khushboogoyal499