-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path100. Same Tree.ts
75 lines (66 loc) · 1.79 KB
/
100. Same Tree.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
{
/**
* Runtime 84 ms Beats 77.43%
* Memory 45.1 MB Beats 5.90%
*/
/**
* Definition for a binary tree node.
*/
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 true;
}
if ((p === null && q !== null) || (p !== null && q === null)) {
return false;
}
let answer = true;
const dfs = (pNode: TreeNode | null, qNode: TreeNode | null) => {
if (!pNode || !qNode || !answer) {
return;
} else {
if (
pNode.val !== qNode.val ||
(pNode.left && pNode.left.val) !== (qNode.left && qNode.left.val) ||
(pNode.right && pNode.right.val) !== (qNode.right && qNode.right.val)
) {
answer = false;
return;
} else {
dfs(pNode.left, qNode.left);
dfs(pNode.right, qNode.right);
}
}
};
dfs(p, q);
return answer;
}
var a = new TreeNode(
0,
new TreeNode(
1,
new TreeNode(3, new TreeNode(7), new TreeNode(8)),
new TreeNode(4, new TreeNode(9), new TreeNode(10))
),
new TreeNode(2, new TreeNode(5, new TreeNode(11)), new TreeNode(6))
);
var b = new TreeNode(
0,
new TreeNode(
1,
new TreeNode(3, new TreeNode(7), new TreeNode(8)),
new TreeNode(4, new TreeNode(9), new TreeNode(10))
),
new TreeNode(2, new TreeNode(5, new TreeNode(11)), new TreeNode(6))
);
console.log(isSameTree(a, b)); // true
}