[LeetCode]题解(python):110-Balanced Binary Tree

题目来源:

  https://leetcode.com/problems/balanced-binary-tree/


 

题意分析:

  判断一棵树是不是平衡树。


 

题目思路:

  如果左子树高度和右子树高度差小于等于1,并且左子树是平衡树,右子树是平衡树,那么这棵树是平衡树。那么我们先用一个新的函数返回树的高度和是否平衡树。


 

代码(python):

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def solve(root):
            if root == None:
                return [0,True]
            tmp1,tmp2 = solve(root.left),solve(root.right)
            if abs(tmp1[0] - tmp2[0]) > 1:
                return [max(tmp1[0],tmp2[0]) + 1,False]
            return [max(tmp1[0],tmp2[0]) + 1,tmp1[1] and tmp2[1]]
        return solve(root)[1]
View Code

 

  

posted @ 2016-03-09 15:35  Ry_Chen  阅读(334)  评论(0编辑  收藏  举报