leetcode 110. balanced Binary Tree
题目
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
代码
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root == None:
return True
left = self.depth(root.left)
right = self.depth(root.right)
return abs(left-right) <= 1 and self.isBalanced(root.left) and self.isBalanced(root.right)
def depth(self, root):
if root == None:
return 0
return max(self.depth(root.left), self.depth(root.right)) + 1
1.定义一个depth函数,用于计算从当前位置起的depth
2.从根节点开始计算其左子树和右子树分别的depth,iterative,两者差距小于1,并且其左子树和右子树都balance,则其为balance
平衡二叉树判断

本文介绍了一种判断二叉树是否平衡的方法。通过递归计算每个节点左右子树的深度,确保任意节点的左右子树深度差不超过1来确定整棵树是否平衡。
247

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



