forked from vns9/binarysearch.com
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathUnivalue Tree Count.cpp
More file actions
51 lines (50 loc) · 1.15 KB
/
Univalue Tree Count.cpp
File metadata and controls
51 lines (50 loc) · 1.15 KB
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
// https://binarysearch.com/problems/Univalue-Tree-Count
/**
* class Tree {
* public:
* int val;
* Tree *left;
* Tree *right;
* };
*/
int ans=0;
bool traverse(Tree* curr){
if(curr==nullptr) return true;
bool leftsub = traverse(curr->left);
bool rightsub = traverse(curr->right);
if(!rightsub||!leftsub) return false;
if(curr->left==nullptr && curr->right==nullptr){
ans++;
return true;
}
else if(curr->left==nullptr && curr->right!=nullptr){
if(curr->val==curr->right->val){
ans++;
return true;
}
else return false;
}
else if(curr->right==nullptr && curr->left!=nullptr){
if(curr->val==curr->left->val){
ans++;
return true;
}
else return false;
}
else{
if(curr->left->val!=curr->right->val || curr->left->val!=curr->val ||curr->val!=curr->right->val){
return false;
}
else{
ans++;
return true;
}
}
return false;
}
int solve(Tree* root) {
traverse(root);
int retans=ans;
ans=0;
return retans;
}