題目:輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹。若左右子樹深度差不超過1則為一顆平衡二叉樹。
思路:
- 使用獲取二叉樹深度的方法來獲取左右子樹的深度
- 左右深度相減,若大於1返回False
- 通過遞歸對每個節點進行判斷,若全部均未返回False,則返回True
class TreeNode(): def __init__(self,x): self.val = x self.left = None self.right = None class Solution: def getDeepth(self,Root): if Root is None: return 0 nright = self.getDeepth(Root.right) nleft = self.getDeepth(Root.left) return max(nright,nleft)+1 def IsBalance_solution(self,pRoot): if pRoot is None: return True right = self.getDeepth(pRoot.right) left = self.getDeepth(pRoot.left) if abs(right - left) > 1: return False return self.IsBalance_solution(pRoot.right) and self.IsBalance_solution(pRoot.left)