Update 0110.平衡二叉树.md

This commit is contained in:
jianghongcheng
2023-05-22 15:38:38 -05:00
committed by GitHub
parent 3818de4610
commit f5329cd4b9

View File

@ -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