-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path5-kyu-fun-with-trees-is-perfect.js
141 lines (118 loc) · 2.62 KB
/
5-kyu-fun-with-trees-is-perfect.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
// 5 kyu | Fun with trees: is perfect
// https://www.codewars.com/kata/fun-with-trees-is-perfect
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
class TreeNode {
constructor(left = null, right = null) {
this.left = left;
this.right = right;
}
static leaf() {
return new TreeNode();
}
static join(left, right) {
return new TreeNode().withChildren(left, right);
}
withLeft(left) {
this.left = left;
return this;
}
withRight(right) {
this.right = right;
return this;
}
withChildren(left, right) {
this.left = left;
this.right = right;
return this;
}
withLeftLeaf() {
return this.withLeft(TreeNode.leaf());
}
withRightLeaf() {
return this.withRight(TreeNode.leaf());
}
withLeaves() {
return this.withChildren(TreeNode.leaf(), TreeNode.leaf());
}
// Added code
static depth(root) {
return !root
? 0
: 1 + Math.max(TreeNode.depth(root.left), TreeNode.depth(root.right));
}
static cnt(root) {
let cnt = 0;
const stack = [root];
while (stack.length) {
const { left, right } = stack.pop();
cnt++;
if (right) stack.push(right);
if (left) stack.push(left);
}
return cnt;
}
static isPerfect(root) {
const depth = TreeNode.depth(root);
if (0 === depth) return true;
const cnt = TreeNode.cnt(root);
if ((1 === depth && 1 === cnt) || (2 === depth && 3 === cnt)) return true;
return depth * 2 + 1 === cnt;
}
}
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
import { strictEqual } from 'assert';
strictEqual(TreeNode.isPerfect(null), true);
strictEqual(TreeNode.isPerfect(TreeNode.leaf().withLeaves()), true);
strictEqual(TreeNode.isPerfect(TreeNode.leaf().withLeftLeaf()), false);
strictEqual(TreeNode.isPerfect(TreeNode.leaf()), true);
// /*
// * full two level tree
// *
// * 0
// * / \
// * 0 0
// * / \ / \
// * 0 0 0 0
// *
// */
strictEqual(
TreeNode.isPerfect(
TreeNode.join(TreeNode.leaf().withLeaves(), TreeNode.leaf().withLeaves()),
),
true,
);
// /*
// * full unbalanced tree
// *
// * 0
// * / \
// * 0 0
// * / \
// * 0 0
// *
// */
strictEqual(
TreeNode.isPerfect(
TreeNode.join(TreeNode.leaf().withLeaves(), TreeNode.leaf()),
),
false,
);
// /*
// * non-full balanced tree
// *
// * 0
// * / \
// * 0 0
// * / \
// * 0 0
// *
// */
strictEqual(
TreeNode.isPerfect(
TreeNode.join(
TreeNode.leaf().withLeftLeaf(),
TreeNode.leaf().withRightLeaf(),
),
),
false,
);