#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;
}
二叉树的基本操作
最新推荐文章于 2022-10-28 22:39:31 发布