其他分享
首页 > 其他分享> > 剑指offer-二叉树

剑指offer-二叉树

作者:互联网

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

  

 

标签:__,right,offer,self,pRoot,getDepth,二叉树
来源: https://www.cnblogs.com/chaojunwang-ml/p/11492215.html