-
Notifications
You must be signed in to change notification settings - Fork 215
/
Copy pathObjC_Easy_100_Same_Tree.m
89 lines (72 loc) · 2.81 KB
/
ObjC_Easy_100_Same_Tree.m
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
78
79
80
81
82
83
84
85
86
87
88
89
/*
https://leetcode.com/problems/same-tree/
#100 Same Tree
Level: easy
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
Inspired by [@JohnWeiGitHub](https://leetcode.com/discuss/3470/seeking-for-better-solution) and [@scott](https://leetcode.com/discuss/22197/my-non-recursive-method)
*/
#import "ObjC_Easy_100_Same_Tree.h"
@implementation ObjC_Easy_100_Same_Tree_Node
- (instancetype)init {
return [self initWithValue:1 left:nil right:nil];
}
- (instancetype)initWithValue:(NSInteger)value left:(ObjC_Easy_100_Same_Tree_Node *)left right:(ObjC_Easy_100_Same_Tree_Node *)right {
if ((self = [super init])) {
_value = value;
_left = left;
_right = right;
}
return self;
}
@end
@implementation ObjC_Easy_100_Same_Tree
// t = O(N), average s = O(logN), worst s = O(N)
+ (BOOL)isSameTreeWithP_recursion:(ObjC_Easy_100_Same_Tree_Node *)p q:(ObjC_Easy_100_Same_Tree_Node *)q {
if (p == nil || q == nil) {
return (p == nil && q == nil);
} else {
return p.value == q.value && [self isSameTreeWithP_recursion:p.left q:q.left] && [self isSameTreeWithP_recursion:p.right q:q.right];
}
}
// t = O(N), average s = O(logN), worst s = O(N)
+ (BOOL)isSameTreeWithP_iteration:(ObjC_Easy_100_Same_Tree_Node *)p q:(ObjC_Easy_100_Same_Tree_Node *)q {
if (p == nil || q == nil) {
return (p == nil && q == nil);
} else {
NSMutableArray *stack_p = [NSMutableArray arrayWithObject:p];
NSMutableArray *stack_q = [NSMutableArray arrayWithObject:q];
while (stack_p.count != 0 && stack_q.count != 0) {
ObjC_Easy_100_Same_Tree_Node *tmp_p = stack_p[0];
[stack_p removeObjectAtIndex:0];
ObjC_Easy_100_Same_Tree_Node *tmp_q = stack_q[0];
[stack_q removeObjectAtIndex:0];
if (tmp_p.value != tmp_q.value) {
return false;
}
if (tmp_p.left != nil) {
[stack_p addObject:tmp_p.left];
}
if (tmp_q.left != nil) {
[stack_q addObject:tmp_q.left];
}
if (stack_p.count != stack_q.count) {
return false;
}
if (tmp_p.right != nil) {
[stack_p addObject:tmp_p.right];
}
if (tmp_q.right != nil) {
[stack_q addObject:tmp_q.right];
}
if (stack_p.count != stack_q.count) {
return false;
}
}
return stack_q.count == stack_q.count;
}
}
+ (BOOL)isSameTreeWithP: (nullable ObjC_Easy_100_Same_Tree_Node *)p q: (nullable ObjC_Easy_100_Same_Tree_Node *)q {
return [self isSameTreeWithP_iteration:p q:q];
}
@end