zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):110 Balanced Binary Tree

    题目来源


    https://leetcode.com/problems/balanced-binary-tree/

    Given a binary tree, determine if it is height-balanced.

    For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.


    题意分析


    Input: a binary tree

    Output: True or False

    Conditions: 判断一颗树是不是平衡树,平衡树的意思是:对于每个节点而言,左右子树的最大深度不超过1


    题目思路


    递归判断。


    AC代码(Python)

     1 # Definition for a binary tree node.
     2 # class TreeNode(object):
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.left = None
     6 #         self.right = None
     7 
     8 class Solution(object):
     9     def Height(self, root):
    10         if root == None:
    11             return 0
    12         return max(self.Height(root.left), self.Height(root.right)) + 1
    13     def isBalanced(self, root):
    14         """
    15         :type root: TreeNode
    16         :rtype: bool
    17         """
    18         if root == None:
    19             return True
    20         if abs(self.Height(root.left) - self.Height(root.right)) <= 1:
    21             return self.isBalanced(root.left) and self.isBalanced(root.right)
    22         else:
    23             return False
  • 相关阅读:
    每天一个linux命令:head(15)
    用设计模式来替代if-else
    每天一个linux命令:less(14)
    每天一个linux命令:more(13)
    每天一个linux命令:nl(12)
    CDN是什么鬼
    ajax跨域问题
    PDO和MySQLi区别与选择?
    php 依赖注入 和 控制反转 php设计模式
    理解 PHP 依赖注入
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5502335.html
Copyright © 2011-2022 走看看