二叉排序树——华科05年

题目描述

在这里插入图片描述

知识点

二叉搜索树的建树二叉树的遍历

结果

在这里插入图片描述

实现

码前思考

  1. 二叉树的建立是 以二叉树的插入操作为基础的
  2. 注意:**不要重复的插入相同数据值!**唉,如果不提示,我可能真的不知道;

代码实现

//简单的二叉树操作
//重复的数据不要进行输出 
#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;
} 

码后反思

  1. 凡是涉及到影响树的结构的操作 都要传地址的
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值