题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
解法1:逐个判断每个节点
1 # -*- coding:utf-8 -*- 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 class Solution: 8 def IsBalanced_Solution(self, pRoot): 9 # write code here 10 if not pRoot: 11 return True 12 if abs(self.tree(pRoot.left) -self.tree(pRoot.right))>1: 13 return False 14 return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right) 15 16 def tree(self,pRoot): 17 # 求深度 18 if not pRoot: 19 return 0 20 if not pRoot.left and not pRoot.right: 21 return 1 22 return max(self.tree(pRoot.left),self.tree(pRoot.right))+1 23 24