剑指 树的深度

二叉树的深度

http://www.nowcoder.com/questionTerminal/435fb86331474282a3499955f0a41e8b

通过递归的方法,先去求左子树的路径长度,再去求右子树的路径长度,看哪一个路径长度大,则返回哪一条路径。

class Solution:
    # 返回 RandomListNode
    def Clone(self, pHead):
        # write code here
        if pHead==None:
            return None

        l=pHead
        while l!=None:
            node=RandomListNode(l.label)

            node.next=l.next
            l.next=node
            l=node.next


        s=pHead
        while s!=None and s.next!=None:
            if s.random:
                s.next.random=s.random.next
            s=s.next.next
        result=p=pHead.next
        #result=RandomListNode(0)
        f=pHead
        while p.next!=None:
            f.next=f.next.next
            p.next=p.next.next

            p=p.next
            f=f.next
        f.next=None
        return result

广度优先搜索,队列中加入一个level变量,注意的是在循环外初始化queue中加入level,在循环内也要记得加入。

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
import collections
class Solution:
    def TreeDepth(self, pRoot):
        # write code here
        if pRoot==None:
            return 0
        queue=collections.deque([(pRoot,0)])


        while queue:
            node,level=queue.popleft()
            level+=1
            if node.left:
                queue.append((node.left,level))
            if node.right:
                queue.append((node.right,level))

        return level
全部评论

相关推荐

不愿透露姓名的神秘牛友
06-27 15:19
简历上能写3个月吗?
码农索隆:大胆写,主要你能把实习经历包装好,可以看一下我这篇帖子https://www.nowcoder.com/share/jump/4888395581180798063
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 18:35
简历上把1个月实习写成了3个月,会进行背调吗?
码农索隆:一个月有一个月的实习经历,三个月有三个月的实习经历
点赞 评论 收藏
分享
05-19 19:57
蚌埠学院 Python
2237:Gpa70不算高,建议只写排名,个人技能不在多而在精,缩到8条以内。项目留一个含金量高的,减少间距弄到一页,硕士简历也就一页,本科不要写很多
实习,投递多份简历没人回...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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