添加(0111.二叉树的最小深度.md):增加typescript版本

This commit is contained in:
Steve2020
2022-02-01 20:04:51 +08:00
parent 97bc7efbb2
commit e4f674c61e

View File

@ -404,6 +404,44 @@ var minDepth = function(root) {
};
```
## TypeScript
> 递归法
```typescript
function minDepth(root: TreeNode | null): number {
if (root === null) return 0;
if (root.left !== null && root.right === null) {
return 1 + minDepth(root.left);
}
if (root.left === null && root.right !== null) {
return 1 + minDepth(root.right);
}
return 1 + Math.min(minDepth(root.left), minDepth(root.right));
}
```
> 迭代法
```typescript
function minDepth(root: TreeNode | null): number {
let helperQueue: TreeNode[] = [];
let resMin: number = 0;
let tempNode: TreeNode;
if (root !== null) helperQueue.push(root);
while (helperQueue.length > 0) {
resMin++;
for (let i = 0, length = helperQueue.length; i < length; i++) {
tempNode = helperQueue.shift()!;
if (tempNode.left === null && tempNode.right === null) return resMin;
if (tempNode.left !== null) helperQueue.push(tempNode.left);
if (tempNode.right !== null) helperQueue.push(tempNode.right);
}
}
return resMin;
};
```
## Swift
> 递归