leetcode【简单】110、平衡二叉树

在这里插入图片描述
思路一:
利用一个算节点高度的函数的函数,对于当前遍历到的节点,首先计算左右子树的高度,如果左右子树的高度差是否不超过 1,再分别递归地遍历左右子节点,并判断左子树和右子树是否平衡。

冗余重复计算很多,效率很低

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isBalanced(self, root: TreeNode) -> bool:
        def height(root):
            if not root:
                return 0
            return max(height(root.left),height(root.right))+1

        if not root:
            return True
        return abs(height(root.left)-height(root.right))<=1 and self.isBalanced(root.left) and self.isBalanced(root.right)

思路二:改进,递归计算节点深度的时候,顺便判断是否平衡,不平衡就退出
(很迷惑,这样做的运行时间反而多了很多)

class Solution:
    def isBalanced(self, root: TreeNode) -> bool:
        def height(root):
            if not root:
                return 0
            lefth=height(root.left)
            righth=height(root.right)
            #如果不平衡就返回-1
            if lefth==-1 or righth==-1 or abs(lefth-righth)>1:
                return -1
            #平衡就返回当前深度
            return max(height(root.left),height(root.right))+1

        return height(root)>=0

猜你喜欢

转载自blog.csdn.net/qq_40707462/article/details/113181507