二叉树的实现和四种遍历

#include<iostream> 
#include<queue> 
using namespace std;

struct node{
	int data;
	node *lchild,*rchild;
	int layer;	//存放树的层次
};

node* newnode(int x){   //生成一个新结点 
	node* r=new node;
	r->data=x;
	r->lchild=r->rchild=NULL;
	return r;
}

void insert(node* &root,int x){   
//插入一个结点 ,修改指针地址,需要引用 
	if(root==NULL){
		root=newnode(x);
		return;
	}
	if(x<root->data){       //这里的规则可以修改 
		insert(root->lchild,x);
	}
	else{
		insert(root->rchild,x);
	}	
}

void search(node* root,int x,int newdata) { 
//查找一个值为x的结点并修改其值为newdata ,修改指针指向的值,不需引用 
	
	if(root->data==x)
	{
		root->data=newdata;
		return; 
	}
	search(root->lchild,x,newdata);
	search(root->rchild,x,newdata);	
}



node * creating(int a[],int n){  //创建二叉树 
	node* root=NULL;
	for(int i=0;i<n;i++)
	insert(root,a[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);
	ineorder(root->rchild);
}

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

void layerorder(node* root) {  //层次遍历并标记层次 
	if(root==NULL)return;
	queue <node*> q;
	 //队列保存原元素的一个副本,这里存指针才能修改layer 
	root->layer=0;
	node* temp=root;	
    q.push(temp);
	while(!q.empty()) {
		temp=q.front();q.pop();
		printf("%d",temp->data);
		if(temp->lchild!=NULL){
			temp->lchild->layer=temp->layer+1;//层次标记 
			q.push(temp->lchild);	
		}
		if(temp->rchild!=NULL){
			temp->rchild->layer=temp->layer+1;
			q.push(temp->rchild);	
		}
	
		
	}
	
}

int main()
{
	int a[]={1, 2, 3,4,5,6} ;
	node* s=creating(a,6) ;
	layerorder(s);
	return 0;
}

实际上二叉树的实现和链表的实现大同小异,对比结构,只是其是左右两个指针,所以又称为二叉链表,而链表有静态实现,故二叉树有有静态实现,了解即可。

发布了63 篇原创文章 · 获赞 6 · 访问量 2025

猜你喜欢

转载自blog.csdn.net/qq_36684096/article/details/104570544