@@ -447,7 +447,63 @@ var countNodes = function(root) {
447
447
};
448
448
```
449
449
450
+ ## TypeScrpt:
451
+
452
+ > 递归法
453
+
454
+ ```typescript
455
+ function countNodes (root: TreeNode | null): number {
456
+ if (root === null) return 0;
457
+ return 1 + countNodes(root.left) + countNodes(root.right);
458
+ };
459
+ ```
460
+
461
+ > 迭代法
462
+
463
+ ```typescript
464
+ function countNodes(root: TreeNode | null): number {
465
+ let helperQueue: TreeNode[] = [];
466
+ let resCount: number = 0;
467
+ let tempNode: TreeNode;
468
+ if (root !== null) helperQueue.push(root);
469
+ while (helperQueue.length > 0) {
470
+ for (let i = 0, length = helperQueue.length; i < length; i++) {
471
+ tempNode = helperQueue.shift()!;
472
+ resCount++;
473
+ if (tempNode.left) helperQueue.push(tempNode.left);
474
+ if (tempNode.right) helperQueue.push(tempNode.right);
475
+ }
476
+ }
477
+ return resCount;
478
+ };
479
+ ```
480
+
481
+ > 利用完全二叉树性质
482
+
483
+ ``` typescript
484
+ function countNodes(root : TreeNode | null ): number {
485
+ if (root === null ) return 0 ;
486
+ let left: number = 0 ,
487
+ right: number = 0 ;
488
+ let curNode: TreeNode | null = root ;
489
+ while (curNode !== null ) {
490
+ left ++ ;
491
+ curNode = curNode .left ;
492
+ }
493
+ curNode = root ;
494
+ while (curNode !== null ) {
495
+ right ++ ;
496
+ curNode = curNode .right ;
497
+ }
498
+ if (left === right ) {
499
+ return 2 ** left - 1 ;
500
+ }
501
+ return 1 + countNodes (root .left ) + countNodes (root .right );
502
+ };
503
+ ```
504
+
450
505
## C:
506
+
451
507
递归法
452
508
``` c
453
509
int countNodes (struct TreeNode* root) {
@@ -538,7 +594,7 @@ func _countNodes(_ root: TreeNode?) -> Int {
538
594
return 1 + leftCount + rightCount
539
595
}
540
596
```
541
-
597
+
542
598
> 层序遍历
543
599
``` Swift
544
600
func countNodes (_ root : TreeNode? ) -> Int {
@@ -564,7 +620,7 @@ func countNodes(_ root: TreeNode?) -> Int {
564
620
return res
565
621
}
566
622
```
567
-
623
+
568
624
> 利用完全二叉树性质
569
625
``` Swift
570
626
func countNodes (_ root : TreeNode? ) -> Int {
0 commit comments