题目:输入一棵二叉树,判断该二叉树是否是平衡二叉树。若左右子树深度差不超过1则为一颗平衡二叉树。
思路:1、使用获取二叉树深度的方法来获取左右子树的深度
2、左右深度相减,若大于1返回False
3、通过递归对每个节点进行判断,若全部均未返回False,则返回True
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getDeepth(self, Root):
if Root is None:
return 0
nright = self.getDeepth(Root.right)
nleft = self.getDeepth(Root.left)
return max(nright, nleft)+1
def IsBalanced_Solution(self, pRoot):
# write code here
if pRoot is None:
return True
right = self.getDeepth(pRoot.right)
left = self.getDeepth(pRoot.left)
if abs(right - left) >1:
return False
return self.IsBalanced_Solution(pRoot.right) and self.IsBalanced_Solution(pRoot.left)
进阶思路:
采用后续遍历,当遍历到根节点时,每个节点只会遍历一次
以下程序无法运行,仅提供思路
class Solution:
def IsBalanced(self, pRoot, depth):
if pRoot is None:
return True
if self.IsBalanced(pRoot.right, right) and self.IsBalanced(pRoot.left, left):
diff = abs(left - right)
if diff <= 1:
depth = max(left, right) +1
return True
return False
def IsBalanced_Solution(self, pRoot):
# write code here
depth = 0
return self.IsBalanced(pRoot, depth)