zoukankan      html  css  js  c++  java
  • 110. 平衡二叉树


    方法一:自底向上

    class Solution(object):
        # 法一:自底向上
        def isBalanced(self, root):
            """
            :type root: TreeNode
            :rtype: bool
            """
            return self.helper(root) >= 0
    
        def helper(self, root):
            if not root:
                return 0
            left = self.helper(root.left)
            right = self.helper(root.right)
            if left == -1 or right == -1 or abs(left - right) > 1:
                return -1
            return max(left, right) + 1
    

    方法二:自顶向下

    class Solution(object):
        # 法二:自顶向下
        def isBalanced(self, root):
            """
            :type root: TreeNode
            :rtype: bool
            """
            if not root:
                return True
    
            # 左、右子树深度
            heightLeft = self.treeDepth(root.left)
            heightRight = self.treeDepth(root.right)
            # 判断左、右子树是否平衡
            resultLeft = self.isBalanced(root.left)
            resultRight = self.isBalanced(root.right)
    
            # 左子树和右子树都是AVL,并且高度相差不大于1,返回真
            if resultLeft and resultRight and abs(heightLeft - heightRight) <= 1:
                return True
            else:
                return False
    
        # 求二叉树的深度
        def treeDepth(self, root):
            if not root:
                return 0
            depthLeft = self.treeDepth(root.left)
            depthRight = self.treeDepth(root.right)
            return depthLeft + 1 if depthLeft > depthRight else depthRight + 1
    
  • 相关阅读:
    MySQL 存储过程
    linux iptables 相关设置
    Ubuntu iptables 设置
    Mac OS 10.12
    解决:cc1.exe: sorry, unimplemented: 64-bit mode not compiled in
    go get golang.org/x/net 安装失败的解决方法!
    Ubuntu16.04
    Ubuntu16.04
    Ubuntu16.04
    在Ubuntu16.04里面安装Gogland!
  • 原文地址:https://www.cnblogs.com/panweiwei/p/13585685.html
Copyright © 2011-2022 走看看