-
Notifications
You must be signed in to change notification settings - Fork 20
/
SameTree.js
57 lines (51 loc) · 1.26 KB
/
SameTree.js
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
/**
* 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.
*
* Accepted.
*/
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}
/**
* @param {TreeNode} p
* @param {TreeNode} q
* @return {boolean}
*/
let isSameTree = function (p, q) {
return p === null && q === null || p !== null && q !== null && p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
};
if (isSameTree(null, null)) {
console.log("pass")
} else {
console.error("failed")
}
let tn1 = new TreeNode(1);
if (isSameTree(null, tn1) === false) {
console.log("pass")
} else {
console.error("failed")
}
if (isSameTree(tn1, null) === false) {
console.log("pass")
} else {
console.error("failed")
}
let tn2 = new TreeNode(2);
if (isSameTree(tn1, tn2) === false) {
console.log("pass")
} else {
console.error("failed")
}
let tn1111 = new TreeNode(1);
tn1111.left = new TreeNode(1);
tn1111.right = new TreeNode(1);
let tn2111 = new TreeNode(1);
tn2111.left = new TreeNode(1);
tn2111.right = new TreeNode(1);
if (isSameTree(tn1111, tn2111)) {
console.log("pass")
} else {
console.error("failed")
}