From ea5a011d783073dc0f98bd5d0a0130c97a02153c Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sat, 5 Feb 2022 13:04:38 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880110.=E5=B9=B3?= =?UTF-8?q?=E8=A1=A1=E4=BA=8C=E5=8F=89=E6=A0=91.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0110.平衡二叉树.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index 9d43407a..8a701bb3 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -627,7 +627,26 @@ var isBalanced = function(root) { }; ``` +## TypeScript + +```typescript +// 递归法 +function isBalanced(root: TreeNode | null): boolean { + function getDepth(root: TreeNode | null): number { + if (root === null) return 0; + let leftDepth: number = getDepth(root.left); + if (leftDepth === -1) return -1; + let rightDepth: number = getDepth(root.right); + if (rightDepth === -1) return -1; + if (Math.abs(leftDepth - rightDepth) > 1) return -1; + return 1 + Math.max(leftDepth, rightDepth); + } + return getDepth(root) !== -1; +}; +``` + ## C + 递归法: ```c int getDepth(struct TreeNode* node) {