using
System;
using
System.Collections.Generic;
class
GFG{
class
Node
{
public
int
data;
public
Node left, right;
};
static
Node newNode(
int
data)
{
Node temp =
new
Node();
temp.data = data;
temp.left = temp.right =
null
;
return
temp;
}
static
List<
int
> storeLeaf(Node root,
List<
int
> arr)
{
if
(root ==
null
)
return
arr;
if
(root.left ==
null
&&
root.right ==
null
)
{
arr.Add(root.data);
return
arr;
}
arr = storeLeaf(root.left, arr);
arr = storeLeaf(root.right, arr);
return
arr;
}
static
void
KSmallest(Node root,
int
k)
{
List<
int
> arr =
new
List<
int
>();
arr = storeLeaf(root, arr);
arr.Sort();
for
(
int
i = 0; i < k; i++)
{
if
(i < arr.Count)
{
Console.Write(arr[i] +
" "
);
}
else
{
break
;
}
}
}
public
static
void
Main(String[] args)
{
Node root = newNode(1);
root.left = newNode(2);
root.left.left = newNode(4);
root.left.left.left = newNode(21);
root.left.right = newNode(5);
root.left.right.right = newNode(8);
root.right = newNode(3);
root.right.left = newNode(6);
root.right.right = newNode(7);
root.right.right.right = newNode(19);
KSmallest(root, 3);
}
}