1. 平衡二叉树
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
解:
要么是一颗空树,要么左右子树都是平衡二叉树且左右子树深度之差不超过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 not pRoot:
return True
res = abs(self.getDepth(pRoot.left) - self.getDepth(pRoot.right))
if res <= 1 and self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right):
return True
return False
def getDepth(self, root):
if not root:
return 0
if not (root.left or root.right):
return 1
return max(self.getDepth(root.left), self.getDepth(root.right)) + 1
原文:https://www.cnblogs.com/chaojunwang-ml/p/11492215.html