题目链接:https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof/
难度:简单
描述:
输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
题解
# 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: TreeNode) -> bool:
def recursion(root):
if root is None:
return 0
left_depth = recursion(root.left)
if left_depth == -1:
return -1
right_depth = recursion(root.right)
if right_depth == -1:
return -1
if abs(left_depth - right_depth) < 2:
return max(left_depth, right_depth) + 1
else:
return -1
return recursion(root) != -1