Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth (e.g., if you have a tree with depth D, you'll have D linked lists). Return a array containing all the linked lists.
Each depth must become its own linked list. DFS into a depth-indexed table works but is not the natural order of the levels.
A level-order pass yields one whole level at a time, which is exactly one list.
A queue holds the current level; popped nodes are appended after a dummy, and children are enqueued. dummy.next is stored at the end of the level. Each node is processed once.
We can use the BFS level order traversal method. For each level, we store the values of the current level's nodes into a list, and then add the list to the result array.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\), where \(n\) is the number of nodes in the binary tree.
/** * 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; } * } */classSolution{publicListNode[]listOfDepth(TreeNodetree){List<ListNode>ans=newArrayList<>();Deque<TreeNode>q=newArrayDeque<>();q.offer(tree);while(!q.isEmpty()){ListNodedummy=newListNode(0);ListNodecur=dummy;for(intk=q.size();k>0;--k){TreeNodenode=q.poll();cur.next=newListNode(node.val);cur=cur.next;if(node.left!=null){q.offer(node.left);}if(node.right!=null){q.offer(node.right);}}ans.add(dummy.next);}returnans.toArray(newListNode[0]);}}
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } *//** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */funclistOfDepth(tree*TreeNode)(ans[]*ListNode){q:=[]*TreeNode{tree}forlen(q)>0{dummy:=&ListNode{}cur:=dummyfork:=len(q);k>0;k--{node:=q[0]q=q[1:]cur.Next=&ListNode{Val:node.Val}cur=cur.Nextifnode.Left!=nil{q=append(q,node.Left)}ifnode.Right!=nil{q=append(q,node.Right)}}ans=append(ans,dummy.Next)}return}