-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbtreeidentical.c
77 lines (62 loc) · 1.98 KB
/
btreeidentical.c
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
74
75
76
77
/* Copyright © 2021-2023 Chee Bin HOH. All rights reserved.
*
* Given the roots of two binary trees, determine if these trees are
* identical or not. Identical trees have the same layout and data at each node.
*/
#include "btree.h"
#include <stdio.h>
int isTreeIdentical(struct TreeNode *left, struct TreeNode *right) {
if (NULL == left || NULL == right)
return left == right;
return left->val == right->val && isTreeIdentical(left->left, right->left) &&
isTreeIdentical(left->right, right->right);
}
int main(int argc, char *argv[]) {
struct TreeNode *root = NULL;
struct TreeNode *other = NULL;
int identical;
root = addTreeNode(root, 5);
root = addTreeNode(root, 3);
root = addTreeNode(root, 7);
root = addTreeNode(root, 4);
other = addTreeNode(other, 5);
other = addTreeNode(other, 3);
other = addTreeNode(other, 7);
other = addTreeNode(other, 4);
printf("1st tree topology:\n");
printf("\n");
printTreeNodeInTreeTopology(root);
printf("\n");
printf("2nd tree topology:\n");
printf("\n");
printTreeNodeInTreeTopology(other);
printf("\n");
identical = isTreeIdentical(root, other);
if (identical)
printf("Both trees are identical\n");
else
printf("Both trees are not identical\n");
// I do not care about memory release as it is a test, but we should have
// freeTree
other = addTreeNode(NULL, 5);
other = addTreeNode(other, 3);
other = addTreeNode(other, 7);
other = addTreeNode(other, 4);
other = addTreeNode(other, 9);
printf("\n");
printf("\n");
printf("2nd tree is changed, the tree topology:\n");
printf("\n");
printTreeNodeInTreeTopology(other);
printf("\n");
identical = isTreeIdentical(root, other);
if (identical)
printf("Both trees are identical\n");
else
printf("Both trees are not identical\n");
printf("\n");
printf("\n");
// I do not care about freeing malloced memory, OS will take care of freeing
// heap that is part of process for this one off program.
return 0;
}