平衡二叉树
输入一棵二叉树,判断该二叉树是否是平衡二叉树
题解:计算了树的最大深度和最小深度,然后判断差值,但是这样时间复杂度是O(n2)
自下而上
# -*- 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 self.maxDepth(pRoot) - self.minDepth(pRoot) >= 2:
return False
else:
return True
def maxDepth(self, pRoot):
if pRoot is None:
return 0
return(max(self.maxDepth(pRoot.left),self.maxDepth(pRoot.right)) + 1)
def minDepth(self, pRoot):
if pRoot is None:
return 0
return(min(self.maxDepth(pRoot.left),self.maxDepth(pRoot.right)) + 1)