zoukankan      html  css  js  c++  java
  • 110. 平衡二叉树

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

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

    一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过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
    返回 false 。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/balanced-binary-tree

    递归水题

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def height(self,root:TreeNode)->int:
            if not root:
                return -1
            return max(self.height(root.left),self.height(root.right))+1
            
        def isBalanced(self, root: TreeNode) -> bool:
            if not root:
                return True
            
            return abs(self.height(root.left)-self.height(root.right))<=1
                and self.isBalanced(root.left) and self.isBalanced(root.right)
  • 相关阅读:
    个人介绍
    实验三
    第二次实验
    实验一
    ATM管理系统
    第二次作业
    实验四 决策树算法及应用
    实验三 朴素贝叶斯算法及应用
    实验二 K-近邻算法及应用
    实验一 感知器及其应用
  • 原文地址:https://www.cnblogs.com/xxxsans/p/13428130.html
Copyright © 2011-2022 走看看