Skip to content

Latest commit

 

History

History
26 lines (23 loc) · 882 Bytes

77. 平衡二叉树.md

File metadata and controls

26 lines (23 loc) · 882 Bytes

输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过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:
        #构建递归,如果是平衡二叉树则返回树的深度否则返回-1
        def recur(root):
            if not root:
                return 0
            left = recur(root.left)
            if left == -1: 
                return -1
            right = recur(root.right)
            if right == -1:
                return -1
            return max(left, right)+1 if abs(left-right) <=1 else -1
    
        return recur(root) != -1