[LeetCode]题解(python):110 Balanced Binary Tree

时间:2021-12-25 21:33:19

题目来源


https://leetcode.com/problems/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.


题意分析


Input: a binary tree

Output: True or False

Conditions: 判断一颗树是不是平衡树,平衡树的意思是:对于每个节点而言,左右子树的最大深度不超过1


题目思路


递归判断。


AC代码(Python)

 # 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 Height(self, root):
if root == None:
return 0
return max(self.Height(root.left), self.Height(root.right)) + 1
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root == None:
return True
if abs(self.Height(root.left) - self.Height(root.right)) <= 1:
return self.isBalanced(root.left) and self.isBalanced(root.right)
else:
return False