输入一棵二叉树,判断该二叉树是否是平衡二叉树。
基本思想:递归。
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def Depth(self, pRoot):
if pRoot == None:
return 0
else:
left = self.Depth(pRoot.left)
right = self.Depth(pRoot.right)
return max(left, right) + 1
def IsBalanced_Solution(self, pRoot):
# write code here
if pRoot == None:
return True
else:
if self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right):
if abs(self.Depth(pRoot.left) - self.Depth(pRoot.right)) <= 1:
return True
else:
return False
上面这种做法会使得有些结点被重复遍历,效率不高。
改进版:每个结点只遍历一遍。
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def IsBalanced(self, pRoot):
# write code here
if pRoot == None:
return True, 0
else:
res_left = self.IsBalanced(pRoot.left)
res_right = self.IsBalanced(pRoot.right)
if res_left[0] and res_right[0]:
if abs(res_left[1] - res_right[1]) <= 1:
return True, max(res_left[1], res_right[1]) + 1
return False, 0
def IsBalanced_Solution(self, pRoot):
# write code here
return self.IsBalanced(pRoot)[0]