110. Balanced Binary Tree

Example 1:

Given the following tree [3,9,20,null,null,15,7]:

    3
   / \
  9  20
    /  \
   15   7

Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

Return false.

# 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):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def getheight(root):
            if root is None:
                return 0
            return max(getheight(root.left),getheight(root.right)) + 1
        try:
            if abs(getheight(root.left) - getheight(root.right)) <=1:
                return self.isBalanced(root.left) and self.isBalanced(root.right)
            else:
                return False
        except:
            return True
posted @ 2018-11-30 15:17  bernieloveslife  阅读(89)  评论(0)    收藏  举报