【Leetcode】Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

class Solution(object):

    def isBalanced(self, root):

        """

        :type root: TreeNode

        :rtype: bool

        """

        if not root:

            return True

        return abs(self.depth(root.left)-self.depth(root.right))<2 and self.isBalanced(root.left) and self.isBalanced(root.right)

    def depth(self, root):

        if not root:

            return 0

        return 1+max(self.depth(root.left), self.depth(root.right))

1 需要另外定义一个函数计算每一个node的深度,这个深度也是用递归方法实现的,root的深度等于1+max(左子树深度,右子树深度)

2 判断是否是平衡的,先判断root.left和root.right是否平衡,还得同时判断isBalanced(root.left)和isBalanced(root.right)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容