import
java.util.ArrayList;
import
java.util.HashMap;
import
java.util.LinkedList;
import
java.util.Map;
import
java.util.Queue;
import
java.util.SortedMap;
import
java.util.TreeMap;
class
GFG{
static
class
Node
{
int
key;
Node left, right;
public
Node(
int
key)
{
this
.key = key;
this
.left =
this
.right =
null
;
}
};
static
class
Pair
{
Node first;
int
second;
public
Pair(Node first,
int
second)
{
this
.first = first;
this
.second = second;
}
}
static
int
KNodeVerticalOrder(Node root,
int
k)
{
if
(root ==
null
|| k ==
0
)
return
-
1
;
int
n =
0
;
int
k_node = -
1
;
SortedMap<Integer,
ArrayList<Integer>> m =
new
TreeMap<Integer,
ArrayList<Integer>>();
int
hd =
0
;
Queue<Pair> que =
new
LinkedList<>();
que.add(
new
Pair(root, hd));
while
(!que.isEmpty())
{
Pair temp = que.poll();
hd = temp.second;
Node node = temp.first;
if
(m.get(hd) ==
null
)
m.put(hd,
new
ArrayList<>());
m.get(hd).add(node.key);
if
(node.left !=
null
)
que.add(
new
Pair(node.left, hd -
1
));
if
(node.right !=
null
)
que.add(
new
Pair(node.right, hd +
1
));
}
for
(Map.Entry<Integer,
ArrayList<Integer>> it : m.entrySet())
{
for
(
int
i =
0
;
i < it.getValue().size();
i++)
{
n++;
if
(n == k)
{
return
it.getValue().get(i);
}
}
}
if
(k_node == -
1
)
return
-
1
;
return
0
;
}
public
static
void
main(String[] args)
{
Node root =
new
Node(
1
);
root.left =
new
Node(
2
);
root.right =
new
Node(
3
);
root.left.left =
new
Node(
4
);
root.left.right =
new
Node(
5
);
root.right.left =
new
Node(
6
);
root.right.right =
new
Node(
7
);
root.right.left.right =
new
Node(
8
);
root.right.right.right =
new
Node(
9
);
root.right.right.left =
new
Node(
10
);
root.right.right.left.right =
new
Node(
11
);
root.right.right.left.right.right =
new
Node(
12
);
int
k =
5
;
System.out.println(KNodeVerticalOrder(root, k));
}
}