110. Balanced Binary Tree
110. Balanced Binary Tree
啊啊啊,今天再做这道题竟然不会了,要设置一个辅助函数,这个函数返回值是根结点的深度,但是如果左子树或者右子树不是平衡树,就返回-1,主函数只要不是-1,就是True
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = Noneclass Solution(object):def isBalanced(self, root):""":type root: TreeNode:rtype: bool"""return self.helper(root) != -1def helper(self, root):if root == None:return 0left = self.helper(root.left)if left == -1:return -1right = self.helper(root.right)if right == -1:return -1if abs(left-right) > 1:return -1return 1 + max(left, right)