日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

leetcode面试题 04.03. 特定深度节点链表(bfs)

發布時間:2023/11/29 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 leetcode面试题 04.03. 特定深度节点链表(bfs) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一棵二叉樹,設計一個算法,創建含有某一深度上所有節點的鏈表(比如,若一棵樹的深度為 D,則會創建出 D 個鏈表)。返回一個包含所有深度的鏈表的數組。示例:輸入:[1,2,3,4,5,null,7,8]1/ \ 2 3/ \ \ 4 5 7/8輸出:[[1],[2,3],[4,5,7],[8]]

代碼

/*** 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) {Queue<TreeNode> queue=new LinkedList<>();ArrayList<ListNode> arrayList=new ArrayList<>();queue.add(tree);while (!queue.isEmpty()){int size=queue.size();ListNode head=new ListNode(0);//建立一個輔助的頭節點ListNode helper=head;for(int i=0;i<size;i++){TreeNode temp=queue.poll();ListNode temp2=new ListNode(temp.val);helper.next=temp2;helper=temp2;if(temp.left!=null) queue.offer(temp.left);if(temp.right!=null) queue.offer(temp.right);}arrayList.add(head.next);}ListNode[] listNodes=new ListNode[arrayList.size()];for(int i=0;i<arrayList.size();i++) listNodes[i]=arrayList.get(i);return listNodes;} } 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的leetcode面试题 04.03. 特定深度节点链表(bfs)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。