题目描述
输入一系列整数,建立二叉排序树,并进行前序,中序,后序遍历。
输入描述
输入第一行包括一个整数n(1<=n<=100)。
接下来的一行包括n个整数。
输出描述
可能有多组测试数据,对于每组数据,将题目所给数据建立一个二叉排序树,并对二叉排序树进行前序、中序和后序遍历。
每种遍历结果输出一行。每行最后一个数据之后有一个空格。
输入中可能有重复元素,但是输出的二叉树遍历序列中重复元素不用输出。
示例
输入
5
1 6 5 9 8
输出
1 6 5 9 8
1 5 6 8 9
5 8 9 6 1
原题地址
总结
构建二叉树时候,要先找到要插入的位置,然后再插入。因为要插入的结点都时叶子结点。
题目要求重复元素不输出,所以再insert()中直接对“= ”的情况不采取任何操作。从而实现过滤掉重复元素的效果。
Code
#include<iostream>
#include<vector>
using namespace std;
vector<int> a;
class Node {
public:
int value;
Node* left;
Node* right;
Node(int val) {
value = val;
left = nullptr;
right = nullptr;
}
};
void insert(Node*& root, int a)//将a插在二叉排序数合适的位置
{
if (root == nullptr)//找到待插入结点,进行插入操作
root = new Node(a);
else//递归查找待插入位置
{
//这里过滤掉重复元素的方法,就是对于有相同的元素采取不插入的操作
if (a < root->value)
insert(root->left, a);
if(a > root->value)
insert(root->right, a);
}
}
//重要代码
Node* creatRoot(int point)//创建一棵二叉排序数
{
Node* root = nullptr;
for (int i = 0; i < a.size(); i++)
{
insert(root, a[i]);
}
return root;
}
void preVisit(Node* root)
{
//根左右
if (root)
{
cout << root->value << " ";
if (root->left != nullptr)
preVisit(root->left);
if (root->right != nullptr)
preVisit(root->right);
}
}
void midVisit(Node* root)
{
//左根右
if (root)
{
if (root->left != nullptr)
midVisit(root->left);
cout << root->value << " ";
if (root->right != nullptr)
midVisit(root->right);
}
}
void backVisit(Node* root)
{
//左右根
if (root)
{
if (root->left)
backVisit(root->left);
if (root->right)
backVisit(root->right);
cout << root->value << " ";
}
}
int main()
{
int n;
int temp = 0;
while (cin >> n)
{
a.clear();
for (int i = 0; i < n; i++)//输入数据
{
cin >> temp;
a.push_back(temp);
}
Node* root = creatRoot(0);
preVisit(root);
cout << endl;
midVisit(root);
cout << endl;
backVisit(root);
cout << endl;
}
return 0;
}