93. 平衡二叉树(回顾)

93. 平衡二叉树

中文English

给定一个二叉树,确定它是高度平衡的。对于这个问题,一棵高度平衡的二叉树的定义是:一棵二叉树中每个节点的两个子树的深度相差不会超过1。 

样例

样例  1:
	输入: tree = {1,2,3}
	输出: true
	
	样例解释:
	如下,是一个平衡的二叉树。
		  1  
		 / \                
		2  3

	
样例  2:
	输入: tree = {3,9,20,#,#,15,7}
	输出: true
	
	样例解释:
	如下,是一个平衡的二叉树。
		  3  
		 / \                
		9  20                
		  /  \                
		 15   7 

	
样例  2:
	输入: tree = {1,#,2,3,4}
	输出: false
	
	样例解释:
	如下,是一个不平衡的二叉树。1的左右子树高度差2
		  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 isBalanced(self, root):
        # write your code here
        if not root:
            return True 
        
     #分治法
if not self.isBalanced(root.left): return False if not self.isBalanced(root.right): return False return abs(self.getMaxHeight(root.left) - self.getMaxHeight(root.right)) <= 1 #返回最大高度,当前节点 def getMaxHeight(self, root): if not root: return 0 return max(self.getMaxHeight(root.left), self.getMaxHeight(root.right)) + 1

 

posted @ 2020-08-01 19:27  风不再来  阅读(110)  评论(0编辑  收藏  举报