描述
输入一系列整数,利用所给数据建立一个二叉搜索树,并输出其前序、中序和后序遍历序列。
输入描述:
第一行一个整数 n,表示输入整数数量。
第二行包含 n 个整数。
输出描述:
共三行,第一行输出前序遍历序列,第二行输出中序遍历序列,第三行输出后序遍历序列。
输入中可能有重复元素,但是输出的二叉树遍历序列中重复元素不用输出。
输入
5
1 6 5 9 8
输出
1 6 5 9 8
1 5 6 8 9
5 8 9 6 1
代码
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
using namespace std;
struct TreeNode {
int data;
TreeNode* leftChild;
TreeNode* rightChild;
};
void insertBST(TreeNode*& root, int data) {
TreeNode* pNewNode = new TreeNode;
pNewNode->data = data;
pNewNode->leftChild = NULL;
pNewNode->rightChild = NULL;
if (root == NULL) {
root = pNewNode;
}
else {
TreeNode* pPre = root;
TreeNode* pCur;
while (true) {
if (data == pPre->data) {
break;
}
else if (data < pPre->data) {
pCur = pPre->leftChild;
if (pCur == NULL) {
pPre->leftChild = pNewNode;
break;
}
else {
pPre = pCur;
}
}
else {
pCur = pPre->rightChild;
if (pCur == NULL) {
pPre->rightChild = pNewNode;
break;
}
else {
pPre = pCur;
}
}
}
}
}
void PreOrder(TreeNode* proot) {
if (proot == NULL) {
return;
}
else {
printf("%d ", proot->data);
PreOrder(proot->leftChild);
PreOrder(proot->rightChild);
}
}
void InOrder(TreeNode* proot) {
if (proot == NULL) {
return;
}
else {
InOrder(proot->leftChild);
printf("%d ", proot->data);
InOrder(proot->rightChild);
}
}
void PostOrder(TreeNode* proot) {
if (proot == NULL) {
return;
}
else {
PostOrder(proot->leftChild);
PostOrder(proot->rightChild);
printf("%d ", proot->data);
}
}
int main() {
int n;
scanf("%d", &n);
TreeNode* root = NULL;
for (int i = 0; i < n; ++i) {
int num;
scanf("%d", &num);
insertBST(root, num);
}
PreOrder(root);
printf("\n");
InOrder(root);
printf("\n");
PostOrder(root);
printf("\n");
return 0;
}