[Python手撕]判斷平衡二叉樹

Duancf發表於2024-09-20
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        
        def height(root):
            if not root:
                return 0

            left = height(root.left)
            if left == -1:
                return -1

            right = height(root.right)
            if right == -1:
                return -1
            
            if abs(left-right)>1:
                return -1
            
            return max(left,right)+1
        
        return height(root) != -1

相關文章