题目描述:
输入一棵节点数为 n 二叉树,判断该二叉树是否是平衡二叉树。
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
平衡二叉树(Balanced Binary Tree),具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
样例解释:
样例二叉树如图,为一颗平衡二叉树
注:我们约定空树是平衡二叉树。
返回值描述:
输出一个布尔类型的值
示例1
输入:{1,2,3,4,5,6,7}
返回值:true
示例2
输入:{}
返回值:true
解题思路:
递归方法:通过比较每个节点的左右子树的最大高度差, 来判断此子树是否是二叉平衡树。
若树的所有子树都平衡时,该树才是平衡二叉树。
Python代码实现:
class Solution:
def IsBalanced_Solution(self , pRoot: TreeNode) -> bool:
# write code here
if not pRoot:
return True
return abs(self.depth(pRoot.left)-self.depth(pRoot.right))<=1 and self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
def depth(self,root):
if not root:
return 0
return max(self.depth(root.left), self.depth(root.right))+1