-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path101.symmetric-tree.c
More file actions
73 lines (62 loc) · 2.14 KB
/
101.symmetric-tree.c
File metadata and controls
73 lines (62 loc) · 2.14 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
66
67
68
69
70
71
72
73
#include <stdlib.h>
#include <stdio.h>
/**
* Definition for a binary tree node.
*/
struct TreeNode
{
int val;
struct TreeNode *left;
struct TreeNode *right;
};
int isChildSymmetric(struct TreeNode *left, struct TreeNode *right)
{
if (left == NULL && right == NULL)
return 1;
if (left == NULL || right == NULL)
return 0;
int outerIsSymmetric = isChildSymmetric(left->left, right->right);
int innerIsSymmetric = isChildSymmetric(left->right, right->left);
if (outerIsSymmetric && innerIsSymmetric && (left->val == right->val))
return 1;
return 0;
}
int isSymmetric(struct TreeNode *root)
{
if (root == NULL)
return 1;
return isChildSymmetric(root->left, root->right);
}
int main(int argc, char const *argv[])
{
// [5,4,4,1,null,null,1,2,null,null,2]
struct TreeNode *rootRightRightLeft = (struct TreeNode *)malloc(sizeof(struct TreeNode));
rootRightRightLeft->val = 2;
rootRightRightLeft->left = rootRightRightLeft->right = NULL;
struct TreeNode *rootRightRight = (struct TreeNode *)malloc(sizeof(struct TreeNode));
rootRightRight->val = 1;
rootRightRight->left = NULL;
rootRightRight->right = rootRightRightLeft;
struct TreeNode *rootLeftLeftLeft = (struct TreeNode *)malloc(sizeof(struct TreeNode));
rootLeftLeftLeft->val = 2;
rootLeftLeftLeft->left = rootLeftLeftLeft->right = NULL;
struct TreeNode *rootLeftLeft = (struct TreeNode *)malloc(sizeof(struct TreeNode));
rootLeftLeft->val = 1;
rootLeftLeft->left = rootLeftLeftLeft;
rootLeftLeft->right = NULL;
struct TreeNode *rootRight = (struct TreeNode *)malloc(sizeof(struct TreeNode));
rootRight->val = 4;
rootRight->left = NULL;
rootRight->right = rootRightRight;
struct TreeNode *rootLeft = (struct TreeNode *)malloc(sizeof(struct TreeNode));
rootLeft->val = 4;
rootLeft->left = rootLeftLeft;
rootLeft->right = NULL;
struct TreeNode *root = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->val = 5;
root->left = rootLeft;
root->right = rootRight;
int result = isSymmetric(root);
printf("%d\n", result);
return 0;
}