• 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
    

      

  • 相关阅读:
    Scala 获取当前时间
    mnist 数据集的识别源码解析
    tf.nn.softmax_cross_entropy_with_logits的用法
    softmax函数
    实现手写体 mnist 数据集的识别任务
    MNIST 数据集
    神经网络之激活函数
    模块化神经网络
    np.c_与np.r_
    学习率的选取-滑动平均
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12922004.html
Copyright © 2020-2023  润新知