forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
56 lines (41 loc) · 1.07 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
/// Source : https://leetcode.com/problems/count-univalue-subtrees/description/
/// Author : liuyubobobo
/// Time : 2018-06-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
/// Time Complexity: O(n^2)
/// Space Complexty: O(h)
class Solution {
public:
int countUnivalSubtrees(TreeNode* root) {
if(root == NULL)
return 0;
int res = 0;
if(root->left != NULL)
res += countUnivalSubtrees(root->left);
if(root->right != NULL)
res += countUnivalSubtrees(root->right);
if(isUnivalTree(root, root->val))
res += 1;
return res;
}
private:
bool isUnivalTree(TreeNode* root, int val){
if(root == NULL)
return true;
if(root->val != val)
return false;
return isUnivalTree(root->left, val) && isUnivalTree(root->right, val);
}
};
int main() {
return 0;
}