import java.io.*;
import java.util.*;
public class GFG {
static class node {
int data;
node left;
node right;
}
static class pair{
int x,y;
pair(int xx, int yy){
this.x=xx;
this.y=yy;
}
}
static class StackPair{
node n;
int x;
StackPair(node nn, int xx){
this.n=nn;
this.x=xx;
}
}
static node newnode(int d)
{
node temp = new node();
temp.left = null;
temp.right = null;
temp.data = d;
return temp;
}
static class IncreasingOrder implements Comparator<pair>{
public int compare(pair p1, pair p2){
if(p1.x>p2.x){
return 1;
}else{
if(p1.x<p2.x){
return -1;
}else{
if(p1.y>p2.y){
return 1;
}else{
if(p1.y<p2.y){
return -1;
}else{
return 0;
}
}
}
}
}
}
static class DecreasingOrder implements Comparator<pair>{
public int compare(pair p1, pair p2){
if(p1.x>p2.x){
return -1;
}else{
if(p1.x<p2.x){
return 1;
}else{
if(p1.y>p2.y){
return -1;
}else{
if(p1.y<p2.y){
return 1;
}else{
return 0;
}
}
}
}
}
}
static void printBST(node root)
{
PriorityQueue<pair> great = new PriorityQueue<>(new DecreasingOrder());
PriorityQueue<pair> small = new PriorityQueue<>(new IncreasingOrder());
Stack<StackPair> st = new Stack<>();
st.push(new StackPair(root,1));
while (!st.isEmpty()) {
StackPair sp = st.pop();
node curr = sp.n;
int level = sp.x;
great.add(new pair(level,curr.data));
small.add(new pair(level,curr.data));
if (curr.left!=null)
st.push(new StackPair(curr.left,level+1));
if (curr.right!=null)
st.push(new StackPair(curr.right,level+1));
}
HashSet<Integer> levelsprinted = new HashSet<>();
while (!small.isEmpty() && !great.isEmpty()) {
int toplevel = small.peek().x;
if (levelsprinted.contains(toplevel))
break;
else
levelsprinted.add(toplevel);
while (!small.isEmpty() && small.peek().x == toplevel) {
System.out.print(small.poll().y + " ");
}
int bottomlevel = great.peek().x;
if (levelsprinted.contains(bottomlevel)) {
break;
}
else {
levelsprinted.add(bottomlevel);
}
while (!great.isEmpty() && great.peek().x == bottomlevel) {
System.out.print(great.poll().y + " ");
}
}
}
public static void main (String[] args) {
node root = newnode(25);
root.left = newnode(20);
root.right = newnode(36);
root.left.left = newnode(10);
root.left.right = newnode(22);
root.left.left.left = newnode(5);
root.left.left.right = newnode(12);
root.right.left = newnode(30);
root.right.right = newnode(40);
root.right.left.left = newnode(28);
root.right.right.left = newnode(38);
root.right.right.right = newnode(48);
printBST(root);
}
}