-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeEqual.js
More file actions
50 lines (40 loc) · 1.09 KB
/
Copy pathBinaryTreeEqual.js
File metadata and controls
50 lines (40 loc) · 1.09 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
// Given two Binary Trees, see if the two trees are equal to each other.
// They are equal if and only if tree1 -> child === tree2 -> child,
// A tree's left and right children can be swapped with each other and still be equal
const expect = require('expect');
const BinaryTree = require('./BinarySearchTree');
function twoEqualBST(bst1, bst2) {
if (bst1 === null) {
return bst2 === null;
}
if (bst2 === null) {
return bst1 === null;
}
if (bst1.value !== bst2.value) {
return false;
}
if (twoEqualBST(bst1.left, bst2.left) && twoEqualBST(bst1.right, bst2.right)) {
return true;
}
if (twoEqualBST(bst1.left, bst2.right) && twoEqualBST(bst1.right, bst2.left)) {
return true;
}
return false;
}
// Test
const Btree1 = new BinaryTree(3);
Btree1.insert(4);
const Btree2 = new BinaryTree(3);
Btree2.insert(4);
const Btree3 = new BinaryTree(3);
Btree3.insert(9);
const testFunction = () => {
expect(
twoEqualBST(Btree1, Btree2)
).toEqual(true);
expect(
twoEqualBST(Btree1, Btree3)
).toEqual(false);
};
testFunction();
console.log('EqualBST tests passed');