频道栏目
首页 > 资讯 > 其他 > 正文

# leetcode 110. balanced Binary Tree

17-08-28        来源:[db:作者]  
收藏   我要投稿

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

代码

# 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
        """
        if root == None:
            return True
        left = self.depth(root.left)
        right = self.depth(root.right)
        return abs(left-right) <= 1 and self.isBalanced(root.left) and self.isBalanced(root.right)

    def depth(self, root):
        if root == None:
            return 0
        return max(self.depth(root.left), self.depth(root.right)) + 1

1.定义一个depth函数,用于计算从当前位置起的depth
2.从根节点开始计算其左子树和右子树分别的depth,iterative,两者差距小于1,并且其左子树和右子树都balance,则其为balance

相关TAG标签
上一篇:九度 OJ 1153:括号匹配问题
下一篇:python3登录azureAD并调用azuregraphapi
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站