File tree Expand file tree Collapse file tree 1 file changed +25
-8
lines changed
count-complete-tree-nodes Expand file tree Collapse file tree 1 file changed +25
-8
lines changed Original file line number Diff line number Diff line change 1
1
import { TreeNode } from "../binary-tree-inorder-traversal/TreeNode.ts" ;
2
2
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 {
4
8
if ( root === null ) return 0 ;
5
9
let left = 0 ,
6
10
right = 0 ;
7
11
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
+ }
11
19
}
20
+
12
21
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
+ }
16
29
}
17
30
if ( left === right ) {
18
31
return 2 ** left - 1 ;
19
32
}
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
+ ) ;
21
38
}
You can’t perform that action at this time.
0 commit comments