查看原题目请点我这里
二叉树遍历的经典题
知识点:二叉排序树建树,前序中序后序遍历。
解题思路
首先建立二叉排序树,关键是记住模板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;
}