思路:
模拟
解答:
package bupt;
import java.util.Scanner;
/*
*@author:Totoro
*@createDate:2020年3月18日下午4:16:16
*/
public class 二叉排序树
{
static point[] tree=new point[105];
static int n;
public static void main(String[] args)
{
Scanner cin=new Scanner(System.in);
int N,x;
while(cin.hasNext())
{
N=cin.nextInt();
n=1;
x=cin.nextInt();
tree[0]=new point(x);
System.out.println(-1);
while(N--!=1)
{
x=cin.nextInt();
insert(x,0);
}
}
}
public static void insert(int x,int pos)
{
if(tree[pos].value>x)
{
if(tree[pos].lc==-1)
{
point p=new point(x);
tree[pos].lc=n;
p.pre=pos;
tree[n++]=p;
System.out.println(tree[pos].value);
}
else
insert(x,tree[pos].lc);
}
else
{
if(tree[pos].rc==-1)
{
point p=new point(x);
tree[pos].rc=n;
p.pre=pos;
tree[n++]=p;
System.out.println(tree[pos].value);
}
else
insert(x,tree[pos].rc);
}
}
public static class point
{
int pre;
int lc,rc;
int value;
public point(int x)
{
value=x;
pre=-1;
lc=-1;
rc=-1;
}
}
}