平衡二叉树
时间限制:1秒 空间限制:32768K 热度指数:177436
算法知识视频讲解
题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
解析
平衡二叉树的性质:
1.它是一棵空树。
2.或它的左右两个子树的高度差的绝对值不超过1。
3.并且左右两个子树都是一棵平衡二叉树。
代码
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def IsBalanced_Solution(self, root):
# write code here
if not root:
return True # 1.注意空树也可以
if abs(self.maxDepth(root.left) - self.maxDepth(root.right)) > 1:
# 2.注意左右字数高度差不超过1
return False
# 3.注意左右子树也是平衡二叉树
return self.IsBalanced_Solution(root.left) and self.IsBalanced_Solution(root.right)
def maxDepth(self, root):
if not root: return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
update:2019年10月7日