-
Notifications
You must be signed in to change notification settings - Fork 0
/
23-100. 相同的树.ts
76 lines (67 loc) · 1.87 KB
/
23-100. 相同的树.ts
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
class TreeNode {
val: number
left: TreeNode | null
right: TreeNode | null
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = (val === undefined ? 0 : val)
this.left = (left === undefined ? null : left)
this.right = (right === undefined ? null : right)
}
}
// 利用先序遍历左树存储在栈中
function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean {
if (!p && !q) return false;
let ans: boolean = true;
let stack: Array<number | null> = [];
deep(p);
deep(q, false);
function deep(tree: TreeNode | null, isLeft: boolean = true) {
if (!tree) {
if (isLeft) {
stack.push(null);
} else {
if (stack.shift() !== null) {
ans = false;
}
}
return
};
if (isLeft) {
stack.push(tree!.val);
} else {
if (stack.shift() !== tree?.val) {
ans = false;
return
}
}
deep(tree!.left, isLeft);
deep(tree!.right, isLeft);
}
return ans
};
function isSameTree1(p: TreeNode | null, q: TreeNode | null): boolean {
// 是否一个为空一个不为空
if ((p === null) !== (q === null)) {
return false
}
// 两个都为空
if (p == null && q == null) return true;
// 都不空
return p?.val === q?.val && isSameTree1(p!.left, q!.left) && isSameTree1(p!.right, q!.right)
}
// 镜像树
function isSameTree2(p: TreeNode | null, q: TreeNode | null): boolean {
// 是否一个为空一个不为空
if ((p === null) !== (q === null)) {
return false
}
// 两个都为空
if (p == null && q == null) return true;
// 都不空
return p?.val === q?.val && isSameTree1(p!.left, q!.right) && isSameTree1(p!.right, q!.left)
}
let p2: TreeNode = new TreeNode(2)
let p: TreeNode = new TreeNode(1, p2)
let q2: TreeNode = new TreeNode(2)
let q: TreeNode = new TreeNode(1, null, q2)
isSameTree(p, q)