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