[LeetCode] Count Univalue Subtrees

250. Count Univalue Subtrees

Given the root of a binary tree, return the number of uni-value subtrees.

A uni-value subtree means all nodes of the subtree have the same value.

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
int ans = 0;
bool eq(TreeNode* root) {
if(!root) return false;
else if(!root->left and !root->right) {
ans++;
return true;
} else if(root->left and root->right) {
bool res = true;
res &= eq(root->left);
res &= eq(root->right);
if(!res) return false;
if(root->val == root->left->val and root->val == root->right->val) {
ans++;
return true;
}
return false;
} else if(root->left) {
bool res = eq(root->left);
if(!res) return false;
if(res && root->left->val == root->val) {
ans++;
return true;
}
return false;
} else {
bool res = eq(root->right);
if(!res) return false;
if(res && root->right->val == root->val) {
ans++;
return true;
}
return false;
}
}
public:
int countUnivalSubtrees(TreeNode* root) {
eq(root);
return ans;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/21/PS/LeetCode/count-univalue-subtrees/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.