
#include "stdafx.h"
#include <iostream>
#include <queue>
#include<stdlib.h>
using namespace std;
typedef struct BiNode
{
int data;
BiNode *Lchil;
BiNode *Rchil;
}BiNode, *BiTree;
bool FindEnd(BiTree root, int num, BiTree upon, BiTree &p)
{
if (root == NULL)
{
p = upon;
return false;
}
else if (root->data == num)
{
p = upon;
return true;
}
else if (num < root->data)
{
return FindEnd(root->Lchil, num, root, p);
}
else if (num > root->data)
{
return FindEnd(root->Rchil, num, root, p);
}
}
void AddNode(BiTree &root, int num)
{
BiTree p;
BiTree newp;
if (FindEnd(root, num, NULL, p) != true)
{
newp = (BiTree)malloc(sizeof(BiNode));
newp->data = num;
newp->Lchil = NULL;
newp->Rchil = NULL;
if (p == NULL)
{
root = newp;
}
else if (num < p->data)
{
p->Lchil = newp;
}
else if (num > p->data)
{
p->Rchil = newp;
}
}
}
void PreOrder(BiTree root)
{
if (root)
{
cout << root->data << " ";
PreOrder(root->Lchil);
PreOrder(root->Rchil);
}
}
void InOrder(BiTree root)
{
if (root)
{
InOrder(root->Lchil);
cout << root->data << " ";
InOrder(root->Rchil);
}
}
void PostOrder(BiTree root)
{
if (root)
{
PostOrder(root->Lchil);
PostOrder(root->Rchil);
cout << root->data << " ";
}
}
void LevelOrder(BiTree root)
{
queue<BiNode *> q;
if (!root) return;
q.push(root);
while (q.empty() == false)
{
BiNode *temp = q.front();
q.pop();
if (temp->Lchil)
{
q.push(temp->Lchil);
}
if (temp->Rchil)
{
q.push(temp->Rchil);
}
cout << temp->data << " ";
}
}
int main()
{
int n;
while (cin >> n)
{
BiTree root = NULL;
for (int i = 0;i<n;i++)
{
int num;
cin >> num;
AddNode(root, num);
}
PreOrder(root);
cout << endl;
InOrder(root);
cout << endl;
PostOrder(root);
cout << endl;
LevelOrder(root);
}
return 0;
}