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

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
 

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

猜你喜欢

转载自www.cnblogs.com/siriusli/p/10376639.html