zoukankan      html  css  js  c++  java
  • LeetCode#110 Balanced Binary Tree

    Problem Definition:

    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.

    这里面临的问题是,既要记录子树的高度,又要记录子树是否平衡。

    Solution 1: 只记录子树是否平衡,每次都重新计算高度,太耗时。

    Solution 2: 用一个tuple来记录高度和平衡。

     1     # @param {TreeNode} root
     2     # @return {boolean}
     3     def isBalanced(root):
     4         b,h=func(root)
     5         return b
     6 
     7     def func(root):
     8         if root==None:
     9             return (True,0)
    10         lb,lh=func(root.left)
    11         rb,rh=func(root.right)
    12         return (abs(lh-rh)<=1 and lb and rb, max(lh,rh)+1)
    13     

    Solution 3: 把这两个变量结合在一起,用一个负数表示不平衡时的高度。

     1     def isBalanced(self, root):
     2         return self.height(root)!=-1
     3 
     4     def height(self,root):
     5         if root==None:
     6             return 0
     7         hl=self.height(root.left)
     8         hr=self.height(root.right)
     9         if hl==-1 or hr==-1 or abs(hl-hr)>1:
    10             return -1
    11         return max(hl,hr)+1
  • 相关阅读:
    5、面试题-测试用例篇
    4、面试题-技术篇
    3、面试题-测试流程
    2、面试题-接口测试用例
    全屏圆角弹出框
    Jquery的each退出循环
    拖动DIV
    head里面的其他标记
    更新字段
    Python---序列化
  • 原文地址:https://www.cnblogs.com/acetseng/p/4665703.html
Copyright © 2011-2022 走看看