mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
Merge pull request #1070 from xiaofei-2020/tree10
添加(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
|
||||
|
||||
> 递归
|
||||
|
Reference in New Issue
Block a user