首页 > 其他 > 详细

110.平衡二叉树

时间:2019-10-09 21:30:21      阅读:93      评论:0      收藏:0      [点我收藏+]
# 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: TreeNode) -> bool:
        if root is None:
            return True
        # 分别定义左右子树的高度
        left_depth = 0
        right_depth = 0
        
        if root.left:
            left_depth = self.get_depth(root.left)
        if root.right:
            right_depth = self.get_depth(root.right)
        if abs(left_depth - right_depth) > 1:
            return False
        else:
            return self.isBalanced(root.left) and self.isBalanced(root.right)

    # 获取某一节点对应树的最大高度
    def get_depth(self, root):
        if root is None:
            return 0
        else:
            return max(self.get_depth(root.left), self.get_depth(root.right))+1

 

110.平衡二叉树

原文:https://www.cnblogs.com/WJZheng/p/11644455.html

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