forked from yubinbai/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
56 lines (49 loc) · 1.19 KB
/
main.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <cstdlib>
using namespace std;
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 (left &&
isSameValue(root, root->left) &&
right &&
isSameValue(root, root->right)) {
++(*count);
return true;
}
return false;
}
bool isSameValue(TreeNode* root, TreeNode* child) {
return child == nullptr || root->val == child->val;
}
};
int main() {
Solution sol;
TreeNode* root = new TreeNode(5);
root->left = new TreeNode(1);
root->left->left = new TreeNode(5);
root->left->right = new TreeNode(5);
root->right = new TreeNode(5);
root->right->right = new TreeNode(5);
cout << sol.countUnivalSubtrees(root) << endl;
return 0;
}