平衡二叉树

一、题目描述

 给定一个二叉树,判断它是否是高度平衡的二叉树

 本题中,一棵高度平衡二叉树定义为:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1

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

class Solution:
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if root == None:
            return True
        if abs(self.count(root.left)-self.count(root.right)) > 1:
            return False
        else:
            if self.isBalanced(root.left) and self.isBalanced(root.right):
                return True
            else:
                return False
        
    def count(self,tree):
            if tree == None:
                return 0
            else:
                return max(self.count(tree.left),self.count(tree.right))+1

  

 

 

 

posted @ 2019-02-10 14:36  1直在路上1  阅读(166)  评论(0编辑  收藏  举报