//非递归实现二叉排序树
#include<iostream>
using namespace std;
struct Node{
Node *lchild; //做孩子
Node *rchild; //右孩子
int value;
};
//创建节点
void createNode(Node *&p, int x)
{
Node *root = p;
Node *pre;
//创建根节点
if(root == NULL)
{
p = new Node;
p ->lchild = p ->rchild = NULL;
p ->value = x;
cout << "-1" << endl;
}
else
{
//找到最终的pre节点
while(root)
{
pre = root;
if(x < root->value)
{
root = root->lchild;
}
else
{
root = root ->rchild;
}
}
//生成新的节点
root = new Node;
root ->lchild = root ->rchild = NULL;
root ->value = x;
//以左或右节点插入
if(x < pre->value)
{
pre ->lchild = root;
}
else
pre->rchild = root;
cout << pre ->value << endl;
}
}
int main()
{
int N;//记录几组测试数据
int tmp;
while(cin >> N)
{
Node *p = NULL;
for(int i= 0; i< N; i++)
{
cin >>tmp;
createNode(p,tmp);
}
}
return 0;
}
//递归形式
#include<iostream>
using namespace std;
#include<stdio.h>
class Node
{
public:
Node(int _value):value(_value){
lchild = rchild = NULL;
}
Node(){
Node(0);
}
int value;
Node *lchild;
Node *rchild;
};
int arr[101];
int N;//记录节点数
Node *findTree(Node *root , int x)
{
if(x < root ->value)
{
if(root ->lchild)
{
return findTree(root->lchild, x);
}
else
{
Node *newNode = new Node(x);
root ->lchild = newNode;
return root;
}
}
else
{
if(root ->rchild)
{
return findTree(root ->rchild,x);
}
else
{
Node* newNode = new Node(x);
root ->rchild = newNode;
return root;
}
}
}
void bulidTree()
{
Node *root = new Node(arr[0]);
cout << -1 << endl;
for(int i =1 ; i<N; i++)
{
Node *father = findTree(root,arr[i]);
cout << father ->value << endl;
}
}
int main()
{
while(cin >> N)
{
for(int i =0; i< N; i++)
{
cin >> arr[i];
}
bulidTree();
}
return 0;
}
/**************************************************************
Problem: 1467
User: itswyy
Language: C++
Result: Accepted
Time:20 ms
Memory:1520 kb
****************************************************************/