https://leetcode-cn.com/problems/balanced-binary-tree/
思路:后序遍历,对root的左右子树递归,每次计算root的左右子树高,然后计算root的高,为左右较高者+1.若左右之差大于1,全局flag为false
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
self.flag = True
self.help(root)
return self.flag
def help(self, root):
if not root:
return 0
lh = self.help(root.left)
rh = self.help(root.right)
height = lh if lh > rh else rh
height += 1
if abs(lh - rh) > 1:
self.flag = False
return height