题目描述
知识点
二叉搜索树的建树、二叉树的遍历
结果
实现
码前思考
- 二叉树的建立是 以二叉树的插入操作为基础的 ;
- 注意:**不要重复的插入相同数据值!**唉,如果不提示,我可能真的不知道;
代码实现
//简单的二叉树操作
//重复的数据不要进行输出
#include "bits/stdc++.h"
using namespace std;
const int maxn = 110;
struct node{
int data;
node* lchild;
node* rchild;
//构造函数
node(int _data):data(_data),lchild(NULL),rchild(NULL){}
};
//记录数据的大小
int n;
//输入数组
int input[maxn];
//插入节点,注意传地址
void insert(node* &root,int x){
//递归边界是查找为NULL,或者查找到了
if(root == NULL){
root = new node(x);
return;
}
//如果已经存在这个节点了
if(root->data == x){
return;
}else{
if(root->data > x){ //如果x小于该节点的值
insert(root->lchild,x);
}else{
insert(root->rchild,x);
}
}
}
node* create(int input[],int n){
node* root = NULL;
for(int i=0;i<n;i++){
insert(root,input[i]);
}
return root;
}
void preOrder(node* root){
if(root == NULL){
return;
}
printf("%d ",root->data);
preOrder(root->lchild);
preOrder(root->rchild);
}
void inOrder(node* root){
if(root == NULL){
return;
}
inOrder(root->lchild);
printf("%d ",root->data);
inOrder(root->rchild);
}
void postOrder(node* root){
if(root == NULL){
return;
}
postOrder(root->lchild);
postOrder(root->rchild);
printf("%d ",root->data);
}
int main(){
while(~scanf("%d",&n)){
//读入数据
for(int i=0;i<n;i++){
scanf("%d",&input[i]);
}
//进行建树
node* root = create(input,n);
//进行前序遍历
preOrder(root);
printf("\n");
//进行中序遍历
inOrder(root);
printf("\n");
//进行后续遍历
postOrder(root);
printf("\n");
}
return 0;
}
码后反思
- 凡是涉及到影响树的结构的操作 都要传地址的。