平衡二叉树 递归 python
时间: 2023-11-11 11:00:52 浏览: 92
好的,我知道了。关于平衡二叉树的递归实现,可以参考以下代码:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
if not root:
return True
left_height = self.get_height(root.left)
right_height = self.get_height(root.right)
if abs(left_height - right_height) > 1:
return False
return self.isBalanced(root.left) and self.isBalanced(root.right)
def get_height(self, node: TreeNode) -> int:
if not node:
return 0
return max(self.get_height(node.left), self.get_height(node.right)) + 1
```
其中,`isBalanced` 函数用于判断一棵二叉树是否平衡,`get_height` 函数用于计算一棵二叉树的高度。
阅读全文