From 0f5b0250a3e55324fa68e8d96bcdf700663950fb Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Thu, 4 May 2023 21:49:12 -0500 Subject: [PATCH] =?UTF-8?q?Update=200110.=E5=B9=B3=E8=A1=A1=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0110.平衡二叉树.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index 804c95eb..a3bc77fb 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -532,6 +532,24 @@ class Solution: else: return 1 + max(left_height, right_height) ``` +递归法精简版: + +```python +class Solution: + def isBalanced(self, root: TreeNode) -> bool: + return self.height(root) != -1 + def height(self, node: TreeNode) -> int: + if not node: + return 0 + left = self.height(node.left) + if left == -1: + return -1 + right = self.height(node.right) + if right == -1 or abs(left - right) > 1: + return -1 + return max(left, right) + 1 +``` + 迭代法: