平衡二叉树 牛客网 剑指Offer
- 题目描述
- 输入一棵二叉树,判断该二叉树是否是平衡二叉树。
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def TreeMaxDepth(self, pRoot):
if pRoot == None:
return 0
return max(self.TreeMaxDepth(pRoot.left),self.TreeMaxDepth(pRoot.right)) + 1
def IsBalanced_Solution(self, pRoot):
if pRoot == None:
return True
if abs(self.TreeMaxDepth(pRoot.right) - self.TreeMaxDepth(pRoot.left)) > 1:
return False
return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)

本文介绍了一种判断二叉树是否为平衡二叉树的方法。通过递归计算每个节点的左右子树的最大深度,并检查其差值是否超过1来确定整棵树是否平衡。
2197

被折叠的 条评论
为什么被折叠?



