剑指offer-平衡二叉树(python)

平衡二叉树的定义:每个节点的左右子树的深度不超过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.TreeDepth(pRoot.left)-self.TreeDepth(pRoot.right))>1:
            return False
        return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
    def TreeDepth(self,pRoot):
        if pRoot is None:
            return 0
        return max(self.TreeDepth(pRoot.left),self.TreeDepth(pRoot.right))+1

猜你喜欢

转载自blog.csdn.net/qq_42738654/article/details/104442454