二叉排序树【华中科技大学】★

二叉树遍历实战
本文介绍了一道经典的二叉树遍历题目,通过实例演示了如何构建二叉排序树并进行前序、中序和后序遍历。文章提供了两种实现方式的代码示例,帮助读者理解二叉树的基本操作。

查看原题目请点我这里
二叉树遍历的经典题
知识点:二叉排序树建树,前序中序后序遍历。

解题思路
首先建立二叉排序树,关键是记住模板insert函数,然后进行前中后遍历。
注意
如果有重复的数据,不用输出,所以在插入的时候要考虑对重复点的处理。

版本1

#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <algorithm>
#include <queue>
#include <cstdio>
#include <cctype>
#include <unordered_map>
#include <map>
using namespace std;
const int N = 105;
typedef pair<int, string> PII;
struct tree{
	int val;
	tree* left, * right;
	tree(int x){
		val = x;
		left = right = nullptr;
	}
};
//建树
void create(tree*& root, int val){
	if(!root){
		root = new tree(val);
		return;
	}else if(val > root->val) 
		create(root->right, val);
	else if(val < root->val)
		create(root->left, val);
} 
//前序 
void preorder(tree* root){
	if(!root) return;
	cout<<root->val<<" ";
	preorder(root->left);
	preorder(root->right);
}
//中序 
void inorder(tree* root){
	if(!root) return;
	inorder(root->left);
	cout<<root->val<<" ";
	inorder(root->right);
}
//后序 
void postorder(tree* root){
	if(!root) return;
	postorder(root->left);
	postorder(root->right);
	cout<<root->val<<" ";
}
int main() {
	int n, x;
	while(cin>>n){
		tree* root = nullptr;
		for(int i = 0; i< n; i++){
			cin>>x;
			create(root, x);	
		}
		preorder(root);
		cout<<endl;
		inorder(root);
		cout<<endl;
		postorder(root);
		cout<<endl;
	}
	
	
	return 0;
}

版本2

#include <cstdio>
#include <cstring>
#include<iostream>
using namespace std;
//创建结构体 
struct node{
	int data;
	node* lchild;
	node* rchild;
};
//前序遍历 
void preorder(node* root){   
	printf("%d ",root->data);
	if(root->lchild != NULL) {
		preorder(root->lchild);
	}
	if(root->rchild != NULL) {
		preorder(root->rchild);
	}
}
//中序遍历 
void inorder(node* root){
	if(root->lchild != NULL) {
		inorder(root->lchild);
	}
	printf("%d ",root->data);
	if(root->rchild != NULL) {
		inorder(root->rchild);
	}
}
//后序遍历 
void postorder(node* root){
	if(root->lchild != NULL) {
		postorder(root->lchild);
	}
	if(root->rchild != NULL) {
		postorder(root->rchild);
	}
	printf("%d ",root->data);
}
void insert(node* &root, int data) { //插入数据 
	if(root == NULL) {
		root = new node;
		root->data = data;
		root->lchild = root->rchild = NULL;
		return; 
	}
	if(data == root->data) { //重复元素不做处理 
		return;
	} 
	if(data < root->data) {
		insert(root->lchild,data);
	}
	else {
		insert(root->rchild,data);
	}
	
} 
int main(){
	int n;
	while(scanf("%d",&n) != EOF) {
		int tmp;
		node* root = NULL;//定义树
		for(int i = 0;i < n;i++){
			scanf("%d",&tmp);
			insert(root,tmp);
		}
		preorder(root);
		printf("\n");
		inorder(root);
		printf("\n");
		postorder(root);
		printf("\n");
	}
	
	
	return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值