输入输出格式
输入描述:
输入包含多组测试数据,每组测试数据两行。
第一行,一个数字N(N<=100),表示待插入的节点数。
第二行,N个互不相同的正整数,表示要顺序插入节点的关键字值,这些值不超过10^8。
输出描述:
输出共N行,每次插入节点后,该节点对应的父亲节点的关键字值。
输入输出样例
输入样例
复制
5
2 5 1 3 4
输出样例:
-1
2
2
5
3
#include<bits/stdc++.h>
using namespace std;
//输入先序、中序遍历结果建树
//输出后序遍历结果
struct treenode{
//数字用char,表示单字符
int num;
int father=-1;
treenode*lchild;
treenode*rchild;
treenode(int data):num(data),lchild(NULL),rchild(NULL){}
};
treenode*insert(treenode*root,treenode*&s){
if(root==NULL){
root=s;
}
else if(root->num<s->num){
s->father=root->num;
root->rchild=insert(root->rchild,s);
}
else if(root->num>s->num){
s->father=root->num;
root->lchild=insert(root->lchild,s);
}
return root;
}
int main(){
int n;
cin>>n;
int data;
treenode*root=NULL;
for(int i=0;i<n;i++){
cin>>data;
treenode*s=new treenode(data);
root=insert(root,s);
cout<<s->father<<endl;
}
return 0;
}