import
java.util.ArrayList;
import
java.util.List;
public
class
GenericTreeToBinaryTree {
public
static
class
TreeNode {
int
val;
TreeNode left,right;
List<TreeNode> children;
public
TreeNode(
int
val)
{
this
.val = val;
this
.children =
new
ArrayList<>();
}
}
public
static
TreeNode convert(TreeNode root)
{
if
(root ==
null
) {
return
null
;
}
if
(root.children.size() ==
0
) {
return
root;
}
if
(root.children.size() ==
1
) {
root.left = convert(root.children.get(
0
));
return
root;
}
root.left = convert(root.children.get(
0
));
root.right = convert(root.children.get(
1
));
List<TreeNode> remainingChildren
= root.children.subList(
2
,
root.children.size());
TreeNode rightTreeRoot = root.right;
while
(remainingChildren.size() >
0
) {
if
(rightTreeRoot.children.size() ==
0
) {
rightTreeRoot.left
= convert(remainingChildren.get(
0
));
}
else
{
rightTreeRoot.right
= convert(remainingChildren.get(
0
));
}
remainingChildren = remainingChildren.subList(
1
, remainingChildren.size());
}
return
root;
}
public
static
void
main(String[] args)
{
TreeNode root =
new
TreeNode(
1
);
root.children.add(
new
TreeNode(
2
));
root.children.add(
new
TreeNode(
3
));
root.children.add(
new
TreeNode(
4
));
root.children.add(
new
TreeNode(
5
));
root.children.get(
0
).children.add(
new
TreeNode(
6
));
root.children.get(
0
).children.add(
new
TreeNode(
7
));
root.children.get(
3
).children.add(
new
TreeNode(
8
));
root.children.get(
3
).children.add(
new
TreeNode(
9
));
TreeNode binaryTreeRoot = convert(root);
printTree(binaryTreeRoot);
}
public
static
void
printTree(TreeNode root)
{
if
(root ==
null
) {
return
;
}
System.out.print(root.val +
" "
);
printTree(root.left);
printTree(root.right);
}
}