Balanced Binary Tree Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as: a binary tree in which the depth of the two subtrees of every node never differ by more than 1.(判断是否是平衡二叉树) Example: 1. 递归 123456789101112131415161718192021 # class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass : def isBalanced(self, root: TreeNode) -> bool: def depth(root): if not root: return 0 return 1 + max(depth(root.left), depth(root.right)) if not root: return True if abs(depth(root.left) - depth(root.right)) > 1: return False return self.isBalanced(root.left) and self.isBalanced(root.right) 赞微海报分享
近期评论