import
java.util.ArrayList;
import
java.util.LinkedList;
import
java.util.Queue;
class
GFG {
static
class
TreeNode<T> {
T data;
ArrayList<TreeNode<T> > children;
TreeNode(T data)
{
this
.data = data;
children =
new
ArrayList<TreeNode<T> >();
}
}
static
TreeNode<Integer> takeInputLevelWise(
int
arr[])
{
int
idx =
1
;
int
rootData = arr[
0
];
TreeNode<Integer> root
=
new
TreeNode<Integer>(rootData);
Queue<TreeNode<Integer> > pendingNodes
=
new
LinkedList<TreeNode<Integer> >();
pendingNodes.add(root);
while
(pendingNodes.size() !=
0
) {
TreeNode<Integer> front = pendingNodes.peek();
pendingNodes.poll();
int
numChild = arr[idx];
idx++;
for
(
int
i =
0
; i < numChild; i++) {
int
childData = arr[idx];
idx++;
TreeNode<Integer> child
=
new
TreeNode<Integer>(childData);
front.children.add(child);
pendingNodes.add(child);
}
}
return
root;
}
static
void
printLevelATNewLine(TreeNode<Integer> root)
{
Queue<TreeNode<Integer> > q
=
new
LinkedList<TreeNode<Integer> >();
q.add(root);
q.add(
null
);
while
(!q.isEmpty()) {
TreeNode<Integer> first = q.peek();
q.poll();
if
(first ==
null
) {
if
(q.isEmpty()) {
break
;
}
System.out.println();
q.add(
null
);
continue
;
}
System.out.print(first.data +
" "
);
for
(
int
i =
0
; i < first.children.size();
i++) {
q.add(first.children.get(i));
}
}
}
static
void
helper(TreeNode<Integer> root,
int
depth)
{
root.data = depth;
for
(
int
i =
0
; i < root.children.size(); i++) {
helper(root.children.get(i), depth +
1
);
}
}
static
void
replaceWithDepthValue(TreeNode<Integer> root)
{
helper(root,
0
);
}
public
static
void
main(String[] args)
{
int
arr[]
= {
10
,
3
,
20
,
30
,
40
,
2
,
40
,
50
,
0
,
0
,
0
,
0
};
TreeNode<Integer> root;
root = takeInputLevelWise(arr);
replaceWithDepthValue(root);
printLevelATNewLine(root);
}
}