leetcode 110. Balanced Binary Tree DFS

来源:互联网 发布:淘宝优惠券怎么用不了 编辑:程序博客网 时间:2024/06/05 11:21

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 = Noneclass Solution(object):    def dfs(self , u):        if not u:            return 0        cntL = 0        if u.left:            cntL = self.dfs(u.left)        cntR = 0        if u.right :            cntR = self.dfs(u.right)        if abs(cntL - cntR) > 1 :            self.cango = False        return 1 + max(cntL , cntR)    def isBalanced(self, root):        self.cango = True        self.dfs(root)        return  self.cangoif __name__ == '__main__':   # three = TreeNode(3)    two = TreeNode(2)    one = TreeNode(1)    one.right = two   # two.left = three    s = Solution()    print(s.isBalanced(one))


原创粉丝点击