题目描述
二叉排序树,也称为二叉查找树。可以是一颗空树,也可以是一颗具有如下特性的非空二叉树:
若左子树非空,则左子树上所有节点关键字值均不大于根节点的关键字值;
若右子树非空,则右子树上所有节点关键字值均不小于根节点的关键字值;
左、右子树本身也是一颗二叉排序树。
现在给你N个关键字值各不相同的节点,要求你按顺序插入一个初始为空树的二叉排序树中,每次插入后成功后,求相应的父亲节点的关键字值,如果没有父亲节点,则输出-1。
输入格式
第一行,一个数字N(N<=100),表示待插入的节点数。
第二行,N个互不相同的正整数,表示要顺序插入节点的关键字值,这些值不超过108。
输出格式
输出共N行,每次插入节点后,该节点对应的父亲节点的关键字值
输入样例
5
2 5 1 3 4
输出样例
-1
2
2
5
3
#include <cstdio>
#include <iostream>
#define MAXSIZE 500
using namespace std;
struct BiNode{
int lc;
int rc;
int data;
int turnOn;
BiNode(){
initNode();
}
void initNode(){
lc=rc=-1;
turnOn=false;
}
};
BiNode Tree[MAXSIZE];
int cursor=0;
int createNode(int data){//return the index of new node
if (cursor+1==MAXSIZE)
return -1;//fail
int p=cursor;
Tree[p].turnOn=true;
Tree[p].data=data;
cursor++;
return p;
}
int insertNode(int &nowRoot,int data,int father){//nowRoot:root index of the BST,data:data for inserting
if (nowRoot!=-1){//Ö¸Õë·Ç¿Õ
if (Tree[nowRoot].data<data)
return insertNode(Tree[nowRoot].rc,data,nowRoot);
else
return insertNode(Tree[nowRoot].lc,data,nowRoot);
}
else{
printf("%d\n",father==-1?-1:Tree[father].data);
return nowRoot=createNode(data);
}
}//return the index of new node
int main(){
int n;
int data,root;
while (scanf("%d",&n)!=EOF){
//initiate
for (int i=0;i<MAXSIZE;i++){
Tree[i].initNode();
}
cursor=0;
root=-1;
//input
for (int i=0;i<n;i++){
scanf("%d",&data);
insertNode(root,data,-1);
}
//debug**
// for (int i=0;i<n;i++){
// printf("%d ",Tree[i].data);
// }
//*******
}
return true;
}