剑指offer 平衡二叉树 python实现

# -*- 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):
        bool_flag, depth = self.IsBalanced(pRoot)
        return bool_flag
        
    def IsBalanced(self, pRoot):
        if not pRoot:
            return True, 0
        bool_left, left_depth = self.IsBalanced(pRoot.left)
        bool_right, right_depth = self.IsBalanced(pRoot.right)
        if bool_left and bool_right:
            diff = left_depth - right_depth
            if -1 <= diff <= 1:
                depth = left_depth
                if diff < 0:
                    depth = right_depth
                return True, depth+1
        return False, 0
        

    原文作者:平衡二叉树
    原文地址: https://blog.csdn.net/z2539329562/article/details/80746516
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞