Leetcode练习(Python):树类:第110题:平衡二叉树:给定一个二叉树,判断它是否是高度平衡的二叉树。

题目:

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

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

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

思路:

递归思路。

程序:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isBalanced(self, root: TreeNode) -> bool:
        if not root:
            return True
        index1 = abs(self.tree_depth(root.left) - self.tree_depth(root.right)) <= 1
        index2 = self.isBalanced(root.left)
        index3 = self.isBalanced(root.right)
        return index1 and index2 and index3
        
    def tree_depth(self, node) -> int:
        left_depth = float("-inf")
        right_depth = float("-inf")
        if not node:
            return 0
        if not (node.left or node.right):
            return 1
        if node.left:
            left_depth = max(self.tree_depth(node.left), left_depth)
        if node.right:
            right_depth = max(self.tree_depth(node.right), right_depth)
        return max(left_depth, right_depth) + 1

  

原文地址:https://www.cnblogs.com/zhuozige/p/12922004.html