二叉树的基本操作

#include<iostream>
#include<queue>

using namespace std;

//二叉树的存储结构 
struct node{
	int data;
	int layer;	//层次 
	node* lchild;
	node* rchild;
};

//新建结点 
node* newNode(int v){
	node* Node = new node;
	Node->data = v;
	Node->lchild = Node->rchild = NULL;
	return Node;
}

//二叉树结点的查找、修改 
void search(node* root, int x, int newdata){
	if(root == NULL){
		return;
	}
	if(root->data == x){
		root->data = newdata;
	}
	search(root->lchild, x, newdata);
	search(root->rchild, x, newdata);
}

//二叉树结点的插入
void insert(node* &root, int x){
	if(root == NULL){
		root = newNode(x);
		return;
	}
	insert(root->lchild, x);
} 

//二叉树的创建 
node* Create(int data[], int n){
	node* root = NULL;
	for(int i = 0; i < n; i++){
		insert(root, data[i]);
	}
	return root;
}

//先序遍历
void preorder(node* root){
	if(root == NULL){
		return;
	}
	printf("%d\n", root->data);
	preorder(root->lchild);
	preorder(root->rchild);
}

//中序遍历 
void inorder(node* root){
	if(root == NULL){
		return;
	}
	inorder(root->lchild);
	printf("%d\n", root->data);
	inorder(root->rchild);
}

//后序遍历 
void postorder(node* root){
	if(root == NULL){
		return;
	}
	postorder(root->lchild);
	postorder(root->rchild);
	printf("%d\n", root->data);
}

//层序遍历
void LayerOrder(node* root){
	queue<node*> q;
	root->layer = 1;
	q.push(root);
	while(!q.empty()){
		node* now = q.front();
		q.pop();
		printf("%d ", now->data);
		if(now->lchild != NULL){
			now->lchild->layer = now->layer + 1;
			q.push(now->lchild);
		}
		if(now->rchild != NULL){
			now->rchild->layer = now->layer + 1;
			q.push(now->rchild);
		}
	}
}

int pre[] = {1,2,4,5,3,6};
int in[] = {4,2,5,1,3,6};
//先序序列和中序序列构建唯一的二叉树
//先序序列区间为[preL, preR],中序序列区间为[inL, inR],返回根结点地址 
node* create(int preL, int preR, int inL, int inR){
	if(preL > preR){
		return NULL;	//先序序列长度小于等于0时,直接返回	
	}
	node* root = new node;	//新建一个新的结点,用来存放当前二叉树的根结点 
	root->data = pre[preL];
	
	int k;
	for(k = inL; k <= inR; k++){
		if(in[k] == pre[preL]){	//在中序序列中找到根结点 
			break;
		}
	}
	int numLeft = k - inL;	//左子树的结点个数 
	
	root->lchild = create(preL + 1, preL + numLeft, inL, k - 1);
	root->rchild = create(preL + numLeft + 1, preR, k + 1, inR);
	
	return root;
} 

int main(){
	int a[5] = {1,2,3,4,5};
	node* root = Create(a, 5);
	search(root, 2, 8);
	LayerOrder(root);
	
	printf("\n");
	LayerOrder(create(0,5,0,5));
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值