首页 > 编程语言 > 详细

平衡二叉树-python

时间:2019-08-10 12:35:59      阅读:81      评论:0      收藏:0      [点我收藏+]

思路:平衡二叉树的左右子树的深度相差不能超过1, 因此可以利用上一题求二叉树的深度的函数,对左右子树求最大深度,如果深度小于1,那么就是平衡二叉树了

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def IsBalanced_Solution(self, pRoot):
        # write code here
        if not pRoot:
            return True
        if abs(self.max_depth(pRoot.left) - self.max_depth(pRoot.right)) > 1:
            return False
        return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
    def max_depth(self, pRoot):
        if not pRoot:
            return 0 
        return max(self.max_depth(pRoot.left), self.max_depth(pRoot.right)) + 1

平衡二叉树-python

原文:https://www.cnblogs.com/dolisun/p/11330946.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!