zoukankan      html  css  js  c++  java
  • 【LeetCode每天一题】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.

    Example 1:

    Given the following tree [3,9,20,null,null,15,7]:

        3
       / 
      9  20
        /  
       15   7

    Return true.

    Example 2:

    Given the following tree [1,2,2,3,3,null,null,4,4]:

           1
          / 
         2   2
        / 
       3   3
      / 
     4   4
    

    Return false.

    思路


      对于平衡二叉树的判断,我们根据定义来进行判断。任意节点的左右子树的高度差不超过1,关于这点我们可以使用求二叉树的最大深度时的思想,只不过这里有一点区别就是我们需要求每一个节点的左右子树的高度然后比较。如果任意一个节点的左右子树都不满足平衡二叉树的定义的话我们就改变标志量的值,最后判断标志量来返回结果。

    解决代码


     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         if not root:        # 节点为空直接返回。
    15             return True
    16         self.flag = False      # 设置标志量
    17         self.GetHeight(root)      # 对每一个节点的左右子树高度进行判断。
    18         
    19         return not self.flag
    20            
    22     def GetHeight(self, root):     
    23         if not root:          #  节点为空直接返回0
    24             return 0
    25         left = self.GetHeight(root.left)     # 当前节点左子树的高度
    26         right = self.GetHeight(root.right)   # 当前节点右子树的高度
    27         if abs(left - right) > 1:               # 计算左右子树的高度差
    28             self.flag = True                   #  不满足时,设置标志量
    29         return max(left, right)+1                  #  最高的节点数
  • 相关阅读:
    《软件架构设计》温昱著读后感(一)
    质量属性II(信息领域热词分析)
    质量属性
    2020寒假学习进度报告16
    2020寒假学习进度报告15
    Nginx运行报错unknown directive ""
    使用ajax的几种方式
    Shiro中@RequiresAuthentication等等注解介绍
    shiro自定义异常无法被捕获总是抛出AuthenticationException解决方案
    java中String和int相互转换常用方法详解
  • 原文地址:https://www.cnblogs.com/GoodRnne/p/10864190.html
Copyright © 2011-2022 走看看