mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
添加(0222.完全二叉树的节点个数.md):增加typescript版本
This commit is contained in:
@ -447,7 +447,63 @@ var countNodes = function(root) {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## TypeScrpt:
|
||||||
|
|
||||||
|
> 递归法
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function countNodes(root: TreeNode | null): number {
|
||||||
|
if (root === null) return 0;
|
||||||
|
return 1 + countNodes(root.left) + countNodes(root.right);
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
> 迭代法
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function countNodes(root: TreeNode | null): number {
|
||||||
|
let helperQueue: TreeNode[] = [];
|
||||||
|
let resCount: number = 0;
|
||||||
|
let tempNode: TreeNode;
|
||||||
|
if (root !== null) helperQueue.push(root);
|
||||||
|
while (helperQueue.length > 0) {
|
||||||
|
for (let i = 0, length = helperQueue.length; i < length; i++) {
|
||||||
|
tempNode = helperQueue.shift()!;
|
||||||
|
resCount++;
|
||||||
|
if (tempNode.left) helperQueue.push(tempNode.left);
|
||||||
|
if (tempNode.right) helperQueue.push(tempNode.right);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return resCount;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
> 利用完全二叉树性质
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function countNodes(root: TreeNode | null): number {
|
||||||
|
if (root === null) return 0;
|
||||||
|
let left: number = 0,
|
||||||
|
right: number = 0;
|
||||||
|
let curNode: TreeNode | null= root;
|
||||||
|
while (curNode !== null) {
|
||||||
|
left++;
|
||||||
|
curNode = curNode.left;
|
||||||
|
}
|
||||||
|
curNode = root;
|
||||||
|
while (curNode !== null) {
|
||||||
|
right++;
|
||||||
|
curNode = curNode.right;
|
||||||
|
}
|
||||||
|
if (left === right) {
|
||||||
|
return 2 ** left - 1;
|
||||||
|
}
|
||||||
|
return 1 + countNodes(root.left) + countNodes(root.right);
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
## C:
|
## C:
|
||||||
|
|
||||||
递归法
|
递归法
|
||||||
```c
|
```c
|
||||||
int countNodes(struct TreeNode* root) {
|
int countNodes(struct TreeNode* root) {
|
||||||
@ -538,7 +594,7 @@ func _countNodes(_ root: TreeNode?) -> Int {
|
|||||||
return 1 + leftCount + rightCount
|
return 1 + leftCount + rightCount
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
> 层序遍历
|
> 层序遍历
|
||||||
```Swift
|
```Swift
|
||||||
func countNodes(_ root: TreeNode?) -> Int {
|
func countNodes(_ root: TreeNode?) -> Int {
|
||||||
@ -564,7 +620,7 @@ func countNodes(_ root: TreeNode?) -> Int {
|
|||||||
return res
|
return res
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
> 利用完全二叉树性质
|
> 利用完全二叉树性质
|
||||||
```Swift
|
```Swift
|
||||||
func countNodes(_ root: TreeNode?) -> Int {
|
func countNodes(_ root: TreeNode?) -> Int {
|
||||||
|
Reference in New Issue
Block a user