Skip to content

Commit 534d941

Browse files
committed
Update index.ts
1 parent e6ddbf1 commit 534d941

File tree

1 file changed

+25
-8
lines changed

1 file changed

+25
-8
lines changed

count-complete-tree-nodes/index.ts

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,38 @@
11
import { TreeNode } from "../binary-tree-inorder-traversal/TreeNode.ts";
22

3-
export default function countNodes(root: TreeNode | null): number {
3+
export default function countNodes(
4+
root: TreeNode | null,
5+
leftDepth?: number,
6+
rightDepth?: number
7+
): number {
48
if (root === null) return 0;
59
let left = 0,
610
right = 0;
711
let curNode: TreeNode | null = root;
8-
while (curNode !== null) {
9-
left++;
10-
curNode = curNode.left;
12+
if (typeof leftDepth !== "undefined") {
13+
left = leftDepth;
14+
} else {
15+
while (curNode !== null) {
16+
left++;
17+
curNode = curNode.left;
18+
}
1119
}
20+
1221
curNode = root;
13-
while (curNode !== null) {
14-
right++;
15-
curNode = curNode.right;
22+
if (typeof rightDepth !== "undefined") {
23+
right = rightDepth;
24+
} else {
25+
while (curNode !== null) {
26+
right++;
27+
curNode = curNode.right;
28+
}
1629
}
1730
if (left === right) {
1831
return 2 ** left - 1;
1932
}
20-
return 1 + countNodes(root.left) + countNodes(root.right);
33+
return (
34+
1 +
35+
countNodes(root.left, left-1) +
36+
countNodes(root.right, undefined, right-1)
37+
);
2138
}

0 commit comments

Comments
 (0)