【leetcode】Python实现-110.平衡二叉树

110.平衡二叉树

描述

【leetcode】Python实现-110.平衡二叉树_第1张图片

我,两个递归,效率不行。

class Solution:
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def Depth(root):
            if root is None:
                return 0
            elif root.left i None and root.right is None:
                return 1
            else:
                return 1 + max(Depth(root.left), Depth(root.right))

        if root is None:
            return True
        if abs(Depth(root.left) - Depth(root,right)) > 1:
            return False
        else:
            return isBalanced(root.left) and isBalanced(root.right)

我的这个版本运行速度太慢了。看看别人的,直接定义一个求高度的函数。若子树不平衡,则返回-1。

        def height(node):
            if not node:return 0
            left = height(node.left)
            right = height(node.right)
            if left == -1 or right == -1 or abs(left-right) > 1:
                return -1

            return max(left,right) + 1
        return height(root) != -1

你可能感兴趣的:(leetcode)