刷题--程序员面试金典--面试题 04.03. 特定深度节点链表(go)

面试题 04.03. 特定深度节点链表

给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D,则会创建出 D 个链表)。返回一个包含所有深度的链表的数组。

 

示例:

输入:[1,2,3,4,5,null,7,8]

        1
       /  \ 
      2    3
     / \    \ 
    4   5    7
   /
  8

输出:[[1],[2,3],[4,5,7],[8]]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/list-of-depth-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


思路:

队列实现层序遍历+构建链表得综合题。

func listOfDepth(tree *TreeNode) []*ListNode {

    res := make([]*ListNode,0)

    if tree == nil {
        return res
    }

    queue := make([]*TreeNode,0)
    queue = append(queue,tree)

    for len(queue) != 0 {
        length := len(queue)
        head := &ListNode{0,nil}
        p := head

        for length > 0 {
            t := queue[0]
            lnode := &ListNode{t.Val,nil}
            p.Next = lnode
            p = p.Next
            if t.Left != nil {
                queue = append(queue,t.Left)
            }
            if t.Right != nil {
                queue = append(queue,t.Right)
            }
            queue = queue[1:]
            length--
        }
        res = append(res,head.Next)
    }

    return res
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值