码迷,mamicode.com
首页 > 其他好文 > 详细

[Lintcode]93. Balanced Binary Tree/[Leetcode]

时间:2019-02-14 20:37:15      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:node   ram   @param   this   python   return   efi   sub   height   

93. Balanced Binary Tree/

  • 本题难度: Easy
  • Topic: Binary Tree

Description

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
Example 1:
Input: tree = {1,2,3}
Output: true

Explanation:
This is a balanced binary tree.
      1  
     / \                
    2  3

Example 2:
Input: tree = {3,9,20,#,#,15,7}
Output: true

Explanation:
This is a balanced binary tree.
      3  
     / \                
    9  20                
      /  \                
     15   7 

Example 3:
Input: tree = {1,#,2,3,4}
Output: false

Explanation:
This is not a balanced tree. 
The height of node 1‘s right sub-tree is 2 but left sub-tree is 0.
      1  
       \                
       2                
      /  \                
     3   4

我的代码

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: The root of binary tree.
    @return: True if this Binary tree is Balanced, or false.
    """

    def balancehigh(self,root):
        if root is None:
            return 0
        left = self.balancehigh(root.left)
        right = self.balancehigh(root.right)
        if left == -1 or right == -1 or abs(left-right)>1:
            return -1
        return 1+max(left,right)
        
    def isBalanced(self, root):
        # write your code here
        return self.balancehigh(root)!=-1
 

思路
仍然是递归。
当一个子树不平衡时,整个二叉树肯定不平衡,否则记录其高度。

[Lintcode]93. Balanced Binary Tree/[Leetcode]

标签:node   ram   @param   this   python   return   efi   sub   height   

原文地址:https://www.cnblogs.com/siriusli/p/10376639.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!