mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 02:53:31 +08:00
添加(0111.二叉树的最小深度.md):增加typescript版本
This commit is contained in:
@ -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
|
## Swift
|
||||||
|
|
||||||
> 递归
|
> 递归
|
||||||
|
Reference in New Issue
Block a user