Skip to content

Commit 24e57b8

Browse files
Merge pull request youngyangyang04#1073 from xiaofei-2020/tree11
添加(0222.完全二叉树的节点个数.md):增加typescript版本
2 parents 9e65340 + 38c8b68 commit 24e57b8

File tree

1 file changed

+58
-2
lines changed

1 file changed

+58
-2
lines changed

problems/0222.完全二叉树的节点个数.md

+58-2
Original file line numberDiff line numberDiff line change
@@ -447,7 +447,63 @@ var countNodes = function(root) {
447447
};
448448
```
449449

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+
450505
## C:
506+
451507
递归法
452508
```c
453509
int countNodes(struct TreeNode* root) {
@@ -538,7 +594,7 @@ func _countNodes(_ root: TreeNode?) -> Int {
538594
return 1 + leftCount + rightCount
539595
}
540596
```
541-
597+
542598
> 层序遍历
543599
```Swift
544600
func countNodes(_ root: TreeNode?) -> Int {
@@ -564,7 +620,7 @@ func countNodes(_ root: TreeNode?) -> Int {
564620
return res
565621
}
566622
```
567-
623+
568624
> 利用完全二叉树性质
569625
```Swift
570626
func countNodes(_ root: TreeNode?) -> Int {

0 commit comments

Comments
 (0)