-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrees-Print Tree Level-wise
More file actions
44 lines (38 loc) · 1.14 KB
/
Trees-Print Tree Level-wise
File metadata and controls
44 lines (38 loc) · 1.14 KB
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
Given a generic tree, print the input tree in level wise order. That is, print the elements at same level in one line (separated by space). Print different levels in differnet lines.
Input format :
Elements in level order form separated by space (as per done in class). Order is -
Root_data, n (No_Of_Child_Of_Root), n children, and so on for every element
Output Format :
Level wise print
Sample Input :
10 3 20 30 40 2 40 50 0 0 0 0
Sample Output :
10
20 30 40
40 50
*****************************Solution********************************
import java.util.*;
public static void printLevelWise(TreeNode<Integer> root){
if (root == null)
return;
Queue<TreeNode<Integer>> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty())
{
Queue<TreeNode<Integer>> q1=q;
ArrayList<TreeNode<Integer>> temp=new ArrayList<>();
while(!q1.isEmpty())
{
TreeNode<Integer> node = q1.poll();
System.out.print(node.data + " ");
for (int i = 0; i < node.children.size(); i++)
{
temp.add(node.children.get(i));
}
}
System.out.println();
q.clear();
for(int i=0;i<temp.size();i++)
q.add(temp.get(i));
}
}