-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsame_tree.c
More file actions
52 lines (47 loc) · 1.3 KB
/
Copy pathsame_tree.c
File metadata and controls
52 lines (47 loc) · 1.3 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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool isSameTree(struct TreeNode* p, struct TreeNode* q){
if(!p || !q) {
return !p && !q;
}
struct TreeNode* p_stack[100] = {0};
struct TreeNode* q_stack[100] = {0};
int p_push = 0;
int q_push = 0;
p_stack[p_push++] = p;
q_stack[q_push++] = q;
while(p_push > 0 && q_push > 0) {
struct TreeNode* p_node = p_stack[--p_push];
struct TreeNode* q_node = q_stack[--q_push];
// check values match
if(p_node->val != q_node->val) {
return false;
}
// check structure matches
if(p_node->right || q_node->right) {
if(p_node->right && q_node->right) {
p_stack[p_push++] = p_node->right;
q_stack[q_push++] = q_node->right;
}
else {
return false;
}
}
if(p_node->left || q_node->left) {
if(p_node->left && q_node->left) {
p_stack[p_push++] = p_node->left;
q_stack[q_push++] = q_node->left;
}
else {
return false;
}
}
}
return true;
}