using
System;
using
System.Collections.Generic;
class
GFG
{
class
Node
{
public
int
key;
public
List<Node> child;
};
static
Node newNode(
int
value)
{
Node nNode =
new
Node();
nNode.key = value;
nNode.child=
new
List<Node>();
return
nNode;
}
static
int
ind;
static
Node BuildKaryTree(
int
[]A,
int
n,
int
k,
int
h)
{
if
(n <= 0)
return
null
;
Node nNode = newNode(A[ind]);
if
(nNode ==
null
)
{
Console.WriteLine(
"Memory error"
);
return
null
;
}
for
(
int
i = 0; i < k; i++)
{
if
(ind < n - 1 && h > 1)
{
ind++;
nNode.child.Add(BuildKaryTree(A, n, k, h - 1));
}
else
{
nNode.child.Add(
null
);
}
}
return
nNode;
}
static
Node BuildKaryTree_1(
int
[] A,
int
n,
int
k,
int
iN)
{
int
height = (
int
)Math.Ceiling(Math.Log((
double
)n * (k - 1) + 1) /
Math.Log((
double
)k));
ind = iN;
return
BuildKaryTree(A, n, k, height);
}
static
void
postord(Node root,
int
k)
{
if
(root ==
null
)
return
;
for
(
int
i = 0; i < k; i++)
postord(root.child[i], k);
Console.Write(root.key +
" "
);
}
public
static
void
Main(String []args)
{
int
ind = 0;
int
k = 3, n = 10;
int
[]preorder = { 1, 2, 5, 6, 7, 3, 8, 9, 10, 4 };
Node root = BuildKaryTree_1(preorder, n, k, ind);
Console.WriteLine(
"Postorder traversal of "
+
"constructed full k-ary tree is: "
);
postord(root, k);
Console.WriteLine();
}
}