平衡二叉树的判断,输入一个二叉树判断它是否是平衡二叉树python
时间: 2023-12-04 07:03:12 浏览: 83
判断二叉树是否是平衡二叉树
4星 · 用户满意度95%
# 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 isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def check_balanced(node):
if not node:
return 0
left_height = check_balanced(node.left)
right_height = check_balanced(node.right)
if left_height == -1 or right_height == -1 or abs(left_height - right_height) > 1:
return -1
return max(left_height, right_height) + 1
return check_balanced(root) != -1
阅读全文