-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunivalued_binary_tree.cpp
More file actions
65 lines (60 loc) · 1.5 KB
/
univalued_binary_tree.cpp
File metadata and controls
65 lines (60 loc) · 1.5 KB
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
/*
* =====================================================================================
*
* Filename: univalued_binary_tree.cpp
*
* Description: Univalued Binary Tree. A binary tree is univalued if every node in
* the tree has the same value. Return true if and only if the given
* tree is univalued.
*
* Version: 1.0
* Created: 02/28/19 07:04:39
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
bool isUnivalTree(TreeNode* root)
{
if (root == NULL)
{
return true;
}
return isUnivalTree(root, root->val);
}
private:
bool isUnivalTree(TreeNode* node, int val)
{
if (node == NULL)
{
return true;
}
if (node->val != val)
{
return false;
}
return isUnivalTree(node->left, node->val) && isUnivalTree(node->right, node->val);
}
};
int main(int argc, char* argv[])
{
TreeNode* root = NULL;
auto is_unival = Solution().isUnivalTree(root);
printf("Is univaled binary tree? %s\n", (is_unival ? "Yes" : "No"));
return 0;
}