题解 | #平衡二叉树#python 解法

平衡二叉树

http://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222

先求高度, 再判断平衡。 我都是用的递归做, 感觉这题可以作为中等

class Solution:
    flag = True
    def IsBalanced_Solution(self, pRoot):
        dict_h = {}
        dict_h[None] = 0

        def height(root):
            if (root == None):
                return 0
            # 如果dict_h [root]存在, 直接取。
            if ((root) in dict_h):
                return dict_h[root]
            else:
                # 不存在, 重新计算
                # if(dict_h.has_key(root.left)):
                if ((root.left) in dict_h):
                    height_left = dict_h[root.left]
                else:
                    height_left = height(root.left)
                # if(dict_h.has_key(root.right)):
                if ((root.right) in dict_h):
                    height_right = dict_h[root.right]
                else:
                    height_right = height(root.right)

                dict_h[root] = max(height_left + 1, height_right + 1)
                return dict_h[root]

        # 假设有height字典

        def dfs(root):
            if (root == None):
                return
            # dict_h[None]
            # print("root.left, dict_h[root.left], root.right, dict_h[root.right]", root.left.val if root.left!=None else root.left, dict_h[root.left], root.right.val if root.right!=None else root.right, dict_h[root.right])
            # print("root.left, dict_h[root.left], root.right, dict_h[root.right]",  dict_h[root.left],  dict_h[root.right], abs(dict_h[root.left] - dict_h[root.right]))
            if (abs(dict_h[root.left] - dict_h[root.right]) <= 1):
                dfs(root.left)
                dfs(root.right)
            #     这里就应该结束。
            else:
                self.flag=False
                return
            # return True

        # write code here
        # 先求高度
        height(pRoot)
        # print("height(root.left)", dict_h[pRoot.left])
        # print("height(root.left)", dict_h[pRoot.left.left])
        # print("height(root.left)", dict_h[pRoot.left.right])
        if(pRoot==None):
            return True
        else:
            dfs(pRoot)
            return self.flag
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-07 11:30
仁者伍敌:kpi都懒得刷了属于是
点赞 评论 收藏
分享
06-26 17:24
已编辑
宁波大学 golang
迷失西雅图:别给,纯kpi,别问我为什么知道
点赞 评论 收藏
分享
来个大佬救一下,为上投了都是石沉大海了,没实习经历的话怕秋招直接进不了面。什么实习这么难找,基本
心态爆炸了:现在正式的岗位都少,实习基本不咋招的,除了大厂,中小企业其实没那么多岗位需求,就算是有,大多都是招一两个廉价劳动力,同时,他们也会希望你一来就能干活的,没时间培训你,就让你了解公司的项目,你了解完就可以开始干活。再者是,很多低质量的实习其实用处没有那么大的。我去年也是找实习找到破防,最后去了一家深圳的小公司实习,工作对我来说很简单,甚至不如我在学校做的项目,秋招的时候,这段实习经历也并没有帮上什么忙,投递简历,依旧非常低的回复率。低回复率是常态,尤其是找实习,找不到,那就把重心放在优化自己的简历和项目,多看八股文,锻炼自己的面试能力,多看别人的面经,自己模拟面试,等秋招的时候,只要有那么寥寥几次,好好抓住那几次机会。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务