首页 > 其他 > 详细

剑指offer-二叉树

时间:2019-09-09 16:11:36      阅读:68      评论:0      收藏:0      [点我收藏+]

1. 平衡二叉树

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

解:

要么是一颗空树,要么左右子树都是平衡二叉树且左右子树深度之差不超过1

# 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
        res = abs(self.getDepth(pRoot.left) - self.getDepth(pRoot.right))
        if res <= 1 and self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right):
            return True
        return False
        
    def getDepth(self, root):
        if not root:
            return 0
        if not (root.left or root.right):
            return 1
        return max(self.getDepth(root.left), self.getDepth(root.right)) + 1

  

 

剑指offer-二叉树

原文:https://www.cnblogs.com/chaojunwang-ml/p/11492215.html

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