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
  • 相关阅读:
    [USACO07DEC]观光奶牛Sightseeing Cows
    洛谷 U3348 A2-回文数
    LOJ #2037. 「SHOI2015」脑洞治疗仪
    1441 士兵的数字游戏
    BZOJ 1108: [POI2007]天然气管道Gaz
    P3047 [USACO12FEB]附近的牛Nearby Cows
    POJ 3061 Subsequence
    Hdu 5776 sum
    1052 最大M子段和
    1288 埃及分数
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5502335.html
Copyright © 2011-2022 走看看