mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-11 04:54:51 +08:00
Update 0110.平衡二叉树.md
This commit is contained in:
@ -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
|
||||
|
Reference in New Issue
Block a user