Skip to content

Commit bdc4a4c

Browse files
committed
Update index.ts
1 parent 065ba52 commit bdc4a4c

File tree

1 file changed

+29
-24
lines changed

1 file changed

+29
-24
lines changed

validate-binary-tree-nodes/index.ts

Lines changed: 29 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -3,30 +3,35 @@ export default function validateBinaryTreeNodes(
33
leftChild: number[],
44
rightChild: number[]
55
): boolean {
6-
const record = new Array(n).fill(0);
7-
const set = new Set(new Array(n).fill(0).map((_, index) => index));
8-
//找到默认的根节点
9-
for (let i = 0; i < n; i++) {
10-
if (leftChild[i] >= 0) {
11-
set.delete(leftChild[i]);
12-
}
13-
if (rightChild[i] >= 0) {
14-
set.delete(rightChild[i]);
15-
}
6+
const degree = Array(n).fill(0);
7+
for (const i of leftChild) {
8+
if (i >= 0) degree[i]++;
169
}
17-
if (set.size != 1) return false;
18-
const q = [...set];
19-
while (q.length) {
20-
let len = q.length;
21-
while (len) {
22-
const i = q.shift() as number;
23-
len--;
24-
//若是当前节点入度大于1则不是正确的二叉树
25-
if (record[i]) return false;
26-
record[i] = 1;
27-
if (leftChild[i] >= 0) q.push(leftChild[i]);
28-
if (rightChild[i] >= 0) q.push(rightChild[i]);
29-
}
10+
for (const i of rightChild) {
11+
if (i >= 0) degree[i]++;
3012
}
31-
return Math.min(...record) == 0 ? false : true;
13+
14+
const zeros = degree.filter((a) => a === 0);
15+
if (
16+
!(
17+
Math.min(...degree) === 0 &&
18+
(n === 1 || Math.max(...degree) === 1) &&
19+
zeros.length === 1
20+
)
21+
)
22+
return false;
23+
24+
const visted = new Set<number>();
25+
26+
const q = [degree.findIndex((a) => a === 0)];
27+
for (const i of q) {
28+
if (visted.has(i)) continue;
29+
30+
visted.add(i);
31+
[leftChild[i], rightChild[i]]
32+
.filter((a) => a >= 0)
33+
.forEach((j) => q.push(j));
34+
}
35+
36+
return visted.size === n;
3237
}

0 commit comments

Comments
 (0)