[DFS]110. Balanced Binary Tree

  • 分类:Tree/DFS
  • 时间复杂度: O(nlogn)/O(n)

110. 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.

代码:

O(nlogn)方法:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if root==None:
            return True
        
        h_left=self.height(root.left)
        h_right=self.height(root.right)
        return abs(h_left-h_right)<=1 and self.isBalanced(root.left) and self.isBalanced(root.right)
     
    def height(self, root):
        if root==None:
            return 0
        else:
            return max(self.height(root.left),self.height(root.right))+1
        

O(n)方法:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if root==None:
            return True
        def height(root):
            if root==None:
                return 0
            h_l=height(root.left)
            h_r=height(root.right)
            if h_l==-1 or h_r==-1 or abs(h_l-h_r)>1:
                return -1
            else:
                return max(h_l,h_r)+1
        return height(root)!=-1


讨论:

1.经典平衡2叉树,用DFS解(也是递归orz)
2.第一种O(nlogn)的方法好解释
3.第二种O(n)的方法是直接检测高度,当高度差>1的时候直接返回-1,直接返回-1到最终,速度快。


110
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 真是突如其来的难受和困惑,我就是我,我对你,对大家要坦然,淡然。太多投入感情是一把自残的快速武器。受伤了,也会感悟...
    他乡流浪人阅读 910评论 0 0
  • 4月,又到了幼升小的火热阶段,印度电影《起跑线》也应时上映,让我们感受到了全世界的父母面对孩子的学习都有着一样的焦...
    跳出温水阅读 2,790评论 0 1
  • 不盲从,不追逐,找准自己的风格。 hello,我是聂梦茵。 我发现大家非常喜欢穿搭文,不过,在写更多穿衣风格之前,...
    聂梦茵阅读 5,157评论 1 6
  • 今天看了一篇文章,深受启发。 我们一直都认为一心多用的人是很厉害的,感觉这样更有成就感,不同时做两次或两件以上的事...
    二小咸阅读 6,588评论 24 34