forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 6
/
count-univalue-subtrees.cpp
38 lines (35 loc) · 971 Bytes
/
count-univalue-subtrees.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
// Time: O(n)
// Space: O(h)
/**
* 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:
int countUnivalSubtrees(TreeNode* root) {
int count = 0;
isUnivalSubtrees(root, &count);
return count;
}
bool isUnivalSubtrees(TreeNode* root, int *count) {
if (root == nullptr) {
return true;
}
bool left = isUnivalSubtrees(root->left, count);
bool right = isUnivalSubtrees(root->right, count);
if (isSame(root, root->left, left) &&
isSame(root, root->right, right)) {
++(*count);
return true;
}
return false;
}
bool isSame(TreeNode* root, TreeNode* child, bool is_uni) {
return child == nullptr || (is_uni && root->val == child->val);
}
};