Python :平衡二叉树

牛客网上的剑指 offer的在线编程:

题目描述:

输入一棵二叉树,判断该二叉树是否是平衡二叉树。

# -*- coding: utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def getDepth(self , Root):
        if Root == None:
            return 0
        ldepth = self.getDepth(Root.left)
        rdepth = self.getDepth(Root.right)
        return max(ldepth, rdepth) + 1

    def IsBalanced_Solution(self, pRoot):
        if not pRoot:
            return True
        ldepth = self.getDepth(pRoot.left)
        rdepth = self.getDepth(pRoot.right)
        diff = ldepth - rdepth
        if diff > 1 or diff < -1:
            return False
        return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)

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