forked from piyush01123/Daily-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsol.cpp
76 lines (58 loc) · 1.36 KB
/
sol.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
#include <iostream>
struct node{
int data;
node *left, *right;
};
node *createNode(int data){
node *temp = new node;
temp->data = data;
temp->left = temp->right = nullptr;
return temp;
}
bool isUnivalTreeUtil(node *root, int data){
if (root==nullptr){
return true;
}
if (root->data==data){
return isUnivalTreeUtil(root->left, data) && isUnivalTreeUtil(root->right, data);
}
return false;
}
bool isUnivalTree(node *root){
return isUnivalTreeUtil(root, root->data);
}
int countUnivalTree(node *root){
if (root==nullptr){
return 0;
}
int ctr1 = countUnivalTree(root->left);
int ctr2 = countUnivalTree(root->right);
if (isUnivalTree(root)){
return 1+ctr1+ctr2;
} else {
return ctr1 + ctr2;
}
}
void test(){
node *root;
root = createNode(0);
root->left = createNode(1);
root->right = createNode(0);
root->right->left = createNode(1);
root->right->right = createNode(0);
root->right->left->left = createNode(1);
root->right->left->right = createNode(1);
std::cout<<countUnivalTree(root)<<'\n';
root = createNode(5);
root->left = createNode(5);
root->right = createNode(5);
root->left->left = createNode(6);
root->left->right = createNode(8);
root->right->left = createNode(9);
root->right->right = createNode(7);
std::cout<<countUnivalTree(root)<<'\n';
}
int main(){
test();
return 0;
}