-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path6-kyu-binary-tree-compare.js
95 lines (75 loc) · 2.53 KB
/
6-kyu-binary-tree-compare.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
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
90
91
92
93
94
95
// 6 kyu | Binary Tree Compare
// https://www.codewars.com/kata/binary-tree-compare
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
/**
* Return true if the binary trees rooted and a and b
* are equal in structure and value
* Return false otherwise
*
* @param {Object} a
* @param {Object} b
* @returns {boolean}
*/
// const compare = (a, b) => JSON.stringify(a) === JSON.stringify(b);
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
/**
* Return true if the binary trees rooted and a and b
* are equal in structure and value
* Return false otherwise
*
* @param {Object} a
* @param {Object} b
* @returns {boolean}
*/
// const compare = (a, b) => {
// if (!a && !b) return true;
// if ((!a && b) || (a && !b)) return false;
// const stack = [{ a, b }];
// while (stack.length) {
// const {
// a: { val: aVal, left: aLeft, right: aRight },
// b: { val: bVal, left: bLeft, right: bRight },
// } = stack.pop();
// if (aVal !== bVal) return false;
// if ((!aRight && bRight) || (aRight && !bRight)) return false;
// if ((!aLeft && bLeft) || (aLeft && !bLeft)) return false;
// if (aRight && bRight) stack.push({ a: aRight, b: bRight });
// if (aLeft && bLeft) stack.push({ a: aLeft, b: bLeft });
// }
// return true;
// };
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
/**
* Return true if the binary trees rooted and a and b
* are equal in structure and value
* Return false otherwise
*
* @param {Object} a
* @param {Object} b
* @returns {boolean}
*/
const compare = (a, b) =>
null === a || null === b
? a === b
: a.val === b.val && compare(a.left, b.left) && compare(a.right, b.right);
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
var aNode = { val: 1, left: null, right: null };
var bNode = { val: 1, left: null, right: null };
var cNode = { val: 2, left: null, right: null };
console.log(!!null);
console.log(!!aNode);
var abcNode = { ...aNode };
abcNode.left = bNode;
abcNode.right = cNode;
var bcaNode = { ...bNode };
bcaNode.left = cNode;
bcaNode.right = aNode;
import { strictEqual } from 'assert';
strictEqual(compare(aNode, bNode), true);
strictEqual(compare(aNode, cNode), false);
strictEqual(compare(aNode, aNode), true);
strictEqual(compare(null, null), true);
strictEqual(compare(aNode, null), false);
strictEqual(compare(abcNode, abcNode), true);
strictEqual(compare(abcNode, bcaNode), false);
strictEqual(compare(abcNode, bNode), false);