110. 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.

 题意:判断一个二叉树是否为平衡二叉树(任意一个节点的左右子树的深度相差不大于1)


  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution(object):
  8. def isBalanced(self, root):
  9. return self.check(root) != -1
  10. def check(self, root):
  11. if root is None:
  12. return 0
  13. left = self.check(root.left)
  14. right = self.check(root.right)
  15. if left == -1 or right == -1 or abs(left - right) > 1:
  16. return -1
  17. return 1 + max(left, right)





posted @ 2017-07-12 00:02  xiejunzhao  阅读(138)  评论(0)    收藏  举报