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

本文介绍了一种算法,该算法可以将给定的二叉树转换为一系列链表,每个链表包含同一深度的所有节点。通过层序遍历的方式实现这一目标,并最终返回包含这些链表的数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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

解题思路

  • 层序遍历树中每层节点
  • 每层节点生成一个链表

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
  public ListNode[] listOfDepth(TreeNode tree) {
    List<ListNode> list = new ArrayList<>();
    Queue<TreeNode> queue = new LinkedList<>();
    queue.add(tree);
    while (!queue.isEmpty()) {
      int size = queue.size();
      ListNode lNode = new ListNode();
      for (int i = 0; i < size; i++) {
        TreeNode tNode = queue.poll();
        lNode.next = new ListNode(tNode.val);
        lNode = lNode.next;
        // 左子树
        if (tNode.left != null) queue.offer(tNode.left);
        // 右子树
        if (tNode.right != null) queue.offer(tNode.right);
        // 将头结点放入list中
        if (i == 0) list.add(lNode);
      }
    }
    return list.toArray(new ListNode[0]);
  }
}

题目来源:力扣(LeetCode)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

胡矣

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值