zoukankan      html  css  js  c++  java
  • 20.leetcode110_balanced_binary_tree

    1.题目描述

    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

    判断一个二叉树是否高度平衡:一种二叉树每个子节点深度之间的差异不会超过1

    2.题目分析

    弄懂所谓的平衡二叉树,真是废了不少力气。平衡二叉树就是指二叉树的同级节点对应的最长长度之间的差不超过1。根据这个思路推理的话,只需要(二叉树)自上向下遍历每一级的最长长度,如果长度差不超过1,遍历下一级;超过1,返回False。最后遍历结束的标志是空节点,如果为空节点,返回True。

     3.解题思路

     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 isBalanced(self, root):
    10         """
    11         :type root: TreeNode
    12         :rtype: bool
    13         """   
    14         def maxdep(node,depth): #返回节点最长长度
    15             if node==None:
    16                 return depth
    17             else:
    18                 depth+=1
    19                 return max(maxdep(node.left,depth),maxdep(node.right,depth))
    20             
    21         if root==None: #遍历结束的标志
    22             return True
    23         else:
    24             d1=maxdep(root.left,0) #返回左节点最长长度
    25             d2=maxdep(root.right,0) #返回右节点最长长度
    26             if abs(d1-d2)<=1: #长度差小于等于1
    27                 return self.isBalanced(root.left) and self.isBalanced(root.right) #判断下一级的左节点与右节点是否平衡
    28             else:
    29                 return False #不平衡,返回False

    4.解题感悟

    做题真是越来越不容易了,但希望自己依然坚持下去。我依然充满信心ヾ(◍°∇°◍)ノ゙

     
  • 相关阅读:
    UVALive 7141 BombX
    CodeForces 722D Generating Sets
    CodeForces 722C Destroying Array
    CodeForces 721D Maxim and Array
    CodeForces 721C Journey
    CodeForces 415D Mashmokh and ACM
    CodeForces 718C Sasha and Array
    CodeForces 635C XOR Equation
    CodeForces 631D Messenger
    田忌赛马问题
  • 原文地址:https://www.cnblogs.com/19991201xiao/p/8437173.html
Copyright © 2011-2022 走看看