-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution008.cpp
More file actions
78 lines (64 loc) · 1.3 KB
/
Copy pathsolution008.cpp
File metadata and controls
78 lines (64 loc) · 1.3 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
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
#include<bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
};
TreeNode* newNode(int data)
{
TreeNode* newnode = new TreeNode;
newnode->val = data;
newnode->left = newnode->right = NULL;
return newnode;
}
bool univalTreesHelper(TreeNode* root,int &univalTree)
{
if(root == NULL)
{
return true;
}
bool left = univalTreesHelper(root->left, univalTree);
bool right = univalTreesHelper(root->right, univalTree);
if(left == false || right == false)
{
return false;
}
if(root->left != NULL && root->val != root->left->val)
{
return false;
}
if(root->right != NULL && root->val != root->right->val)
{
return false;
}
univalTree++;
return true;
}
int univalTreesCount(TreeNode* root)
{
int univalTree = 0;
univalTreesHelper(root, univalTree);
return univalTree;
}
int main()
{
/*
0
/ \
1 0
/ \
1 0
/ \
1 1
*/
TreeNode* root = newNode(0);
root->left = newNode(1);
root->right = newNode(0);
root->right->left = newNode(1);
root->right->right = newNode(0);
root->right->left->left = newNode(1);
root->right->left->right = newNode(1);
cout << univalTreesCount(root) << endl;
return 0;
}