【Leetcode_总结】110. 平衡二叉树 - python

Q:

给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

示例 1:

给定二叉树 [3,9,20,null,null,15,7]

    3
   / \
  9  20
    /  \
   15   7

返回 true 。

示例 2:

给定二叉树 [1,2,2,3,3,null,null,4,4]

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

链接:https://leetcode-cn.com/problems/balanced-binary-tree/description/

思路:此题利用了 二叉树的最大深度 的部分代码,逐一遍历节点,判断子树是否是平衡二叉树

代码:

# 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):
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True
        if root.right and root.left:
            if abs(self.maxDepth(root.right) - self.maxDepth(root.left)) <= 1 :
                return self.isBalanced(root.right) and self.isBalanced(root.left)
            else:
                return False
        if not root.left:
            if abs(self.maxDepth(root.right)) <= 1:
                return self.isBalanced(root.right)
            else:
                return False
        if not root.right:
            if abs(self.maxDepth(root.left)) <= 1:
                return self.isBalanced(root.left)
            else:
                return False
            
    def maxDepth(self, root):
        if not root:
            return 0
        else:
            return max(self.maxDepth(root.left) + 1, self.maxDepth(root.right) + 1)

猜你喜欢

转载自blog.csdn.net/maka_uir/article/details/86228632