-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathUnivalSubtrees.cpp
More file actions
37 lines (28 loc) · 861 Bytes
/
UnivalSubtrees.cpp
File metadata and controls
37 lines (28 loc) · 861 Bytes
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool checkUnival(TreeNode * root,int &count){
if(root==NULL)return true;
bool left=checkUnival(root->left,count);
bool right=checkUnival(root->right,count);
if(left==false || right==false)return false;
if(root->left!=NULL && root->left->val!=root->val)return false;
if(root->right!=NULL && root->right->val!=root->val)return false;
count++;
return true;
}
bool isUnivalTree(TreeNode* root) {
int count=0;
bool ans= checkUnival(root,count);
// cout<<count; This gives number of subtrees that are unival.
return ans;
}
};