[LeetCode]题解(python):110 Balanced Binary Tree
题目来源
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)
1 # Definition for a binary tree node. 2 # class TreeNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution(object): 9 def Height(self, root): 10 if root == None: 11 return 0 12 return max(self.Height(root.left), self.Height(root.right)) + 1 13 def isBalanced(self, root): 14 """ 15 :type root: TreeNode 16 :rtype: bool 17 """ 18 if root == None: 19 return True 20 if abs(self.Height(root.left) - self.Height(root.right)) <= 1: 21 return self.isBalanced(root.left) and self.isBalanced(root.right) 22 else: 23 return False