平衡二叉树

# 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
            
posted @ 2021-03-08 11:04  KbMan  阅读(18)  评论(0编辑  收藏  举报