【剑指offer】平衡二叉树[Python]

题目要求:输入一棵二叉树,判断该二叉树是否是平衡二叉树。

思路:递归问题,判断每一个节点构成的树是否为平衡二叉树,有不是的则记为0,是的则记为1,故最后如果list中有0存在则说明有不是平衡二叉树的节点,则返回false

但是,有重复遍历的节点,复杂度太高了~以后写的时候优化一下

第一次代码:

class Solution:

    def TreeDepth(self, root,list_len,list_node):
        if root:
            list_node.append(root)
            if root.left:
                self.TreeDepth(root.left,list_len,list_node)
            if root.right:
                self.TreeDepth(root.right,list_len,list_node)
            if not root.left and not root.right:
                list_len.append(len(list_node))
            list_node.pop()
    def Judge(self, root,balan_solu):
        left_depth,right_depth = 0,0
        if root: 
            if root.left:
                list_len = []
                list_node = []
                self.TreeDepth(root.left,list_len,list_node)
                left_depth = max(list_len)
            if root.right:
                list_len = []
                list_node = []
                self.TreeDepth(root.right,list_len,list_node)
                right_depth = max(list_len)
            if abs(left_depth-right_depth)<=1:
                balan_solu.append(1)
            else:
                balan_solu.append(0)
            if root.left:
                self.Judge(root.left, balan_solu)
            if root.right:
                self.Judge(root.right, balan_solu)


    def IsBalanced_Solution(self, pRoot):
        # write code here
        balan_solu = []
        if pRoot:
            self.Judge(pRoot,balan_solu)
        if 0 in balan_solu:
            return False
        else:
            return True
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值