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