华中科技大学复试 二叉排序树(重要)

题目描述

输入一系列整数,建立二叉排序树,并进行前序,中序,后序遍历。

输入描述

输入第一行包括一个整数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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值