剑指 树的深度

二叉树的深度

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
全部评论

相关推荐

我:“加班需要有加班工资。” hr:“为什么?” 哈哈哈哈哈哈哈离大谱
juntenor:你确实太理想化了,对社会不了解呀。这个和HR没有关系,这是国内特色,不然怎么还会有外包就这种逆天的存在呢。
点赞 评论 收藏
分享
“校招”、“3-5年经验”
xiaolihuamao:逆向工程不是搞外挂的吗,好像现在大学生坐牢最多的就是诈骗罪和非法侵入计算机系统罪,发美金,还居家办公,就是怕被一锅端,
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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