平衡二叉树

# 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 get_depth(root):
            if not root: return 0
            left_depth = get_depth(root.left)
            right_depth = get_depth(root.right)

            if abs(left_depth - right_depth) > 1:
                return -1

            if left_depth == -1 or right_depth == -1:
                return -1
            return 1 + max(left_depth, right_depth)
        
        result = get_depth(root)
        if result == -1:
            return False
        return True
            
原文地址:https://www.cnblogs.com/KbMan/p/14498560.html