想到要涉及到树的deepth,立刻想到了上一节做过的计算树的最大深度的函数 return max(self.depth(pRoot.left), self.depth(pRoot.right)) + 1, 此刻可以调用
算法流程:
通过比较每个节点的左右子树的最大高度差, 来判断此子树是否是二叉平衡树。 若树的所有子树都平衡时,该树才是平衡二叉树。
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def IsBalanced_Solution(self, pRoot):
# write code here
if pRoot == None:
return True
# 高度差不能大于1,并且左右子树也是同样高度差要小于等于1
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, pRoot):
if not pRoot: return 0
# 左右子树中高度较大的作为当前节点高度
return max(self.depth(pRoot.left), self.depth(pRoot.right)) + 1
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def IsBalanced_Solution(self, pRoot):
# write code here
if pRoot == None:
return True
# 高度差不能大于1,并且左右子树也是同样高度差要小于等于1
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, pRoot):
if not pRoot: return 0
# 左右子树中高度较大的作为当前节点高度
return max(self.depth(pRoot.left), self.depth(pRoot.right)) + 1