题目描述:
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
知识点回顾:
平衡二叉树的定义:
任何节点的左右子树高度差都不超过1的二叉树。
思路:
从下到上(从底到顶),分别判断某节点的左右子树是否为平衡二叉树,即根据该结点的左右子树高度差判断是否平衡。
Python实现1:
// An highlighted block
class Solution:
def IsBalanced_Solution(self, pRoot):
# write code here
self.flag = True
self.tree_Iteration(pRoot)
return self.flag
def tree_Iteration(self, pRoot):
if not pRoot or self.flag==False:
return 0
left = self.tree_Iteration(pRoot.left)
right = self.tree_Iteration(pRoot.right)
if abs(left-right)>1:
self.flag = False
return left+1 if left>right else right+1
https://blog.csdn.net/u010005281/article/details/79718391
python实现2:
// An highlighted block
class Solution:
def IsBalanced_Solution(self, pRoot):
if not pRoot: return True
left = self.TreeDepth(pRoot.left)
right = self.TreeDepth(pRoot.right)
if abs(left - right) > 1:
return False
return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
def TreeDepth(self, pRoot):
if not pRoot: return 0
left = self.TreeDepth(pRoot.left)
right = self.TreeDepth(pRoot.right)
return max(left, right) + 1