*[剑指offer] 平衡二叉树

题目内容

https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222?tpId=13&tqId=11192&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

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


题目思路

我们可以考虑采用累积的方法来判断一棵树到底是不是平衡二叉树。从根部开始一层一层的向上传递。对于叶节点它的左右都是0,自己是1。在写递归的时候我遇到的问题是绝对值判断返回TF和返回左右侧的数值到底应该怎么布置。最后选择在主函数中负责判断T F,另一个辅助函数中之判断这个点的最大深度。


程序代码

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

猜你喜欢

转载自blog.csdn.net/u010929628/article/details/91523335
今日推荐