From 46571a3b9c619ac39c93becab1c1325fe211b545 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Mon, 31 Jan 2022 14:51:28 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880104.=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E6=9C=80=E5=A4=A7=E6=B7=B1=E5=BA=A6?= =?UTF-8?q?.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0104.二叉树的最大深度.md | 48 +++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index 7038598b..6875ec74 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -598,7 +598,55 @@ var maxDepth = function(root) { }; ``` +## TypeScript: + +> 二叉树的最大深度: + +```typescript +// 后续遍历(自下而上) +function maxDepth(root: TreeNode | null): number { + if (root === null) return 0; + return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; +}; + +// 前序遍历(自上而下) +function maxDepth(root: TreeNode | null): number { + function recur(node: TreeNode | null, count: number) { + if (node === null) { + resMax = resMax > count ? resMax : count; + return; + } + recur(node.left, count + 1); + recur(node.right, count + 1); + } + let resMax: number = 0; + let count: number = 0; + recur(root, count); + return resMax; +}; + +// 层序遍历(迭代法) +function maxDepth(root: TreeNode | null): number { + let helperQueue: TreeNode[] = []; + let resDepth: number = 0; + let tempNode: TreeNode; + if (root !== null) helperQueue.push(root); + while (helperQueue.length > 0) { + resDepth++; + for (let i = 0, length = helperQueue.length; i < length; i++) { + tempNode = helperQueue.shift()!; + if (tempNode.left) helperQueue.push(tempNode.left); + if (tempNode.right) helperQueue.push(tempNode.right); + } + } + return resDepth; +}; +``` + + + ## C + 二叉树最大深度递归 ```c int maxDepth(struct TreeNode* root){