题目描述
输入描述:
输入包含多组测试数据,每组测试数据两行。 第一行,一个数字N(N<=100),表示待插入的节点数。 第二行,N个互不相同的正整数,表示要顺序插入节点的关键字值,这些值不超过10^8。
输出描述:
输出共N行,每次插入节点后,该节点对应的父亲节点的关键字值。
输入
5 2 5 1 3 4
输出
-1 2 2 5
3
#include<iostream>
using namespace std;
struct node
{
int x;
node * lchild;
node * rchild;
}Tree[110];
int size=0;
node* create()
{
Tree[size].lchild=Tree[size].rchild;
return &Tree[size++];
}
int flag=true;
node * build(node* tree,int x)
{
if(tree==NULL)
{
if(flag)
{
cout<<"-1"<<endl;
flag=false;
}
tree=create();
tree->x=x;
return tree;
}
else if(x>tree->x)
{
if(tree->rchild==NULL)
cout<<tree->x<<endl;
tree->rchild=build(tree->rchild,x);
}
else if(x<tree->x)
{
if(tree->lchild==NULL)
cout<<tree->x<<endl;
tree->lchild=build(tree->lchild,x);
}
return tree;
}
int main()
{
int n,x;
node *tree;
while(cin>>n)
{
tree=NULL;
for(int i=0;i<n;i++)
{
cin>>x;
tree=build(tree,x);
}
}
}