From f5329cd4b913d73f049e6b30f7d2a3a8a2a90770 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Mon, 22 May 2023 15:38:38 -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 | 48 ++++++++++++++++++++++++++++++-- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index a3bc77fb..c0561e10 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -553,6 +553,52 @@ class Solution: 迭代法: +```python +class Solution: + def getDepth(self, cur): + st = [] + if cur is not None: + st.append(cur) + depth = 0 + result = 0 + while st: + node = st[-1] + if node is not None: + st.pop() + st.append(node) # 中 + st.append(None) + depth += 1 + if node.right: + st.append(node.right) # 右 + if node.left: + st.append(node.left) # 左 + + else: + node = st.pop() + st.pop() + depth -= 1 + result = max(result, depth) + return result + + def isBalanced(self, root): + st = [] + if root is None: + return True + st.append(root) + while st: + node = st.pop() # 中 + if abs(self.getDepth(node.left) - self.getDepth(node.right)) > 1: + return False + if node.right: + st.append(node.right) # 右(空节点不入栈) + if node.left: + st.append(node.left) # 左(空节点不入栈) + return True + +``` + +迭代法精简版: + ```python class Solution: def isBalanced(self, root: Optional[TreeNode]) -> bool: @@ -576,8 +622,6 @@ class Solution: height_map[real_node] = 1 + max(left, right) return True ``` - - ### Go ```Go