輸入一棵二叉樹的根節(jié)點(diǎn),判斷該樹是不是平衡二叉樹。如果某二叉樹中任意節(jié)點(diǎn)的左右子樹的深度相差不超過1,那么它就是一棵平衡二叉樹。
示例 1:
給定二叉樹 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回 true 。
示例 2:
給定二叉樹 [1,2,2,3,3,null,null,4,4]
1
/ \
2 2
/ \
3 3
/ \
4 4
返回 false 。
限制:
1 <= 樹的結(jié)點(diǎn)個(gè)數(shù) <= 10000
注意:本題與主站 110 題相同:https://leetcode-cn.com/problems/balanced-binary-tree/
上一題的延伸
函數(shù)寫在函數(shù)里面的時(shí)候,不用self,如果寫在class里面就加self,有self引用的時(shí)候就self.
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def maxDepth(root):
if not root:
return 0
left = maxDepth(root.left) + 1
right = maxDepth(root.right) + 1
return max(left, right)
if not root:
return True
if abs(maxDepth(root.right) - maxDepth(root.left)) >= 2:
return False
return self.isBalanced(root.left) and self.isBalanced(root.right)
上面的另外一種寫法
```python
class Solution:
def maxDepth(self, root):
if not root:
return 0
left = self.maxDepth(root.left) + 1
right = self.maxDepth(root.right) + 1
return max(left, right)
def isBalanced(self, root: TreeNode) -> bool:
if not root:
return True
if abs(self.maxDepth(root.right) - self.maxDepth(root.left)) >= 2:
return False
return self.isBalanced(root.left) and self.isBalanced(root.right)