leetcode_balanced binary tree

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.
(判断是否是平衡二叉树)

Example:

1. 递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class :
def isBalanced(self, root: TreeNode) -> bool:
def depth(root):
if not root:
return 0
return 1 + max(depth(root.left), depth(root.right))

if not root:
return True

if abs(depth(root.left) - depth(root.right)) > 1:
return False

return self.isBalanced(root.left) and self.isBalanced(root.right)