【leetcode❤python】110. Balanced Binary Tree

#-*- coding: UTF-8 -*-
#平衡二叉树
# 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):
    isbalanced=True  
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if root==None:return True
        if root.left==None and root.right==None:return True
        self.dfs(root)
        return self.isbalanced
    
    def dfsDepth(self,root):
        if root==None:return 0
        leftDepth=self.dfsDepth(root.left)
        rightDepth=self.dfsDepth(root.right)
        
        return leftDepth+1 if leftDepth >rightDepth else (rightDepth+1)

    def dfs(self,root):
        if root==None:return
        leftDepth=self.dfsDepth(root.left)
        rightDepth=self.dfsDepth(root.right)
        if abs(leftDepth-rightDepth)>1:
            self.isbalanced=False
        else:
            self.dfs(root.left)
            self.dfs(root.right)

上一篇:docker命令


下一篇:POJ 2442 Sequence 优先队列