# -*- 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
剑指offer 平衡二叉树 python实现
最新推荐文章于 2023-04-30 12:14:36 发布