-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBST2-Level wise linkedlist
67 lines (59 loc) · 1.86 KB
/
BST2-Level wise linkedlist
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
Given a binary tree, write code to create a separate linked list for each level. You need to return the array which contains head of each level linked list.
Input format :
The first line of input contains data of the nodes of the tree in level order form. The data of the nodes of the tree is separated by space. If any node does not have left or right child, take -1 in its place. Since -1 is used as an indication whether the left or right nodes exist, therefore, it will not be a part of the data of any node.
Output format :
Each level linked list is printed in new line (elements are separated by space).
Constraints:
Time Limit: 1 second
Sample Input 1:
5 6 10 2 3 -1 -1 -1 -1 -1 9 -1 -1
Sample Output 1:
5
6 10
2 3
9
*****************************Solution**************************
import java.util.*;
private static ArrayList<LinkedListNode<Integer>> arr= new ArrayList<LinkedListNode<Integer>>();
public static ArrayList<LinkedListNode<Integer>> constructLinkedListForEachLevel(BinaryTreeNode<Integer> root){
if(root==null)
return null;
Queue<BinaryTreeNode<Integer>> nodeToprint = new LinkedList<BinaryTreeNode<Integer>>();
nodeToprint.add(root);
nodeToprint.add(null);
LinkedListNode<Integer> head=null, tail=null;
while(!nodeToprint.isEmpty())
{
BinaryTreeNode<Integer> front=nodeToprint.poll();
if(front==null)
{
if(nodeToprint.isEmpty())
break;
else
{
nodeToprint.add(null);
tail.next=null;
tail=tail.next;
head=null;
}
}
else{
if(head==null)
{
head=new LinkedListNode<Integer>(front.data);
tail=head;
arr.add(head);
}
else
{
tail.next=new LinkedListNode<Integer>(front.data);
tail=tail.next;
}
if(front.left!=null)
nodeToprint.add(front.left);
if(front.right!=null)
nodeToprint.add(front.right);
}
}
return arr;
}