diff --git a/problems/0111.二叉树的最小深度.md b/problems/0111.二叉树的最小深度.md index a439322a..224caa5e 100644 --- a/problems/0111.二叉树的最小深度.md +++ b/problems/0111.二叉树的最小深度.md @@ -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 > 递归