forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain4.cpp
66 lines (50 loc) · 1.35 KB
/
main4.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
57
58
59
60
61
62
63
64
65
66
/// Source : https://leetcode.com/problems/count-univalue-subtrees/description/
/// Author : liuyubobobo
/// Time : 2019-03-02
#include <iostream>
using namespace std;
/// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/// Recursive
/// Treat null as univalue subtree and make the implementation much more concise :-)
///
/// Time Complexity: O(n)
/// Space Complexty: O(h)
class Solution {
private:
int result = 0;
public:
int countUnivalSubtrees(TreeNode* root) {
dfs(root);
return result;
}
private:
bool dfs(TreeNode* node){
if(!node) return true;
bool isLeft = dfs(node->left), isRight = dfs(node->right);
bool ok = isLeft && (!node->left || node->val == node->left->val) &&
isRight && (!node->right || node->val == node->right->val);
if(ok) result ++;
return ok;
}
};
int main() {
// 5
// / \
// 1 5
// / \ \
// 5 5 5
TreeNode *root = new TreeNode(5);
root->left = new TreeNode(1);
root->right = new TreeNode(5);
root->left->left = new TreeNode(5);
root->left->right = new TreeNode(5);
root->right->right = new TreeNode(5);
cout << Solution().countUnivalSubtrees(root) << endl;
return 0;
}