using
System;
using
System.Collections;
using
System.Collections.Generic;
class
GFG
{
public
class
TreeNode {
public
int
data;
public
ArrayList children;
public
TreeNode(
int
data)
{
this
.data = data;
this
.children =
new
ArrayList();
}
};
public
static
TreeNode removeLeaf(TreeNode root)
{
if
(root==
null
) {
return
null
;}
if
(root.children.Count==0){
return
null
;}
for
(
int
i = 0; i < root.children.Count; i++) {
TreeNode child= (TreeNode)root.children[i];
if
(child.children.Count == 0) {
for
(
int
j = i; j < root.children.Count - 1; j++)
{
root.children[j]= root.children[j + 1];
}
root.children.RemoveAt(root.children.Count - 1);
i--;
}
}
for
(
int
i = 0; i < root.children.Count; i++)
{
root.children[i]=removeLeaf((TreeNode)root.children[i]);
}
return
root;
}
static
void
printTheTree(TreeNode root)
{
if
(root ==
null
)
return
;
Console.Write(root.data+
" :"
);
for
(
int
i = 0; i < root.children.Count; i++)
Console.Write(((TreeNode)root.children[i]).data +
" "
);
Console.WriteLine();
for
(
int
i = 0; i < root.children.Count; i++)
printTheTree((TreeNode)root.children[i]);
}
public
static
void
Main(
string
[]args)
{
TreeNode root =
new
TreeNode(5);
TreeNode child1 =
new
TreeNode(1);
root.children.Add(child1);
TreeNode child11 =
new
TreeNode(15);
child1.children.Add(child11);
TreeNode child2 =
new
TreeNode(2);
root.children.Add(child2);
TreeNode child21 =
new
TreeNode(4);
TreeNode child22 =
new
TreeNode(5);
child2.children.Add(child21);
child2.children.Add(child22);
TreeNode child3 =
new
TreeNode(3);
root.children.Add(child3);
TreeNode child31 =
new
TreeNode(6);
child3.children.Add(child31);
TreeNode child4 =
new
TreeNode(8);
root.children.Add(child4);
root=removeLeaf(root);
printTheTree(root);
}
}