二叉树的遍历

void Preorder(node* root){                                
	if(root==NULL){
		return ;
	}
	cout<<root->data<<" ";
	Preorder(root->lchild);                                 //递归

	Preorder(root->rchild);
}
void Inorder(node* root){
	if(root==NULL){
		return ;
	}
	Inorder(root->lchild);
	cout<<root->data<<" ";
	Inorder(root->rchild);
}
void Postorder(node* root){
	if(root==NULL){
		return ;
	}
	Postorder(root->lchild);
	Postorder(root->rchild);
	cout<<root->data<<" ";
}
void Lorder(node* root){                                          //层序相当于BFS
	queue<node*> q;
	q.empalce(root);
	while(!q.empty()){
		node* n=q.front();
		q.pop();
		cout<<n->data<<" ";
		if(n->lchild!=NULL){
			q.emplace(n->lchild);
		}
		if(n->rchild!=NULL){
			q.emplace(n->rchild);
		}
	}
	return ;
}

struct node{
	int data,layer;
	node* lchild;
	node* rchild;
};

void Lorder2(node* root){
	queue<node*> q;
	root->layer=1;
	q.emplace(root);
	while(!q.empty()){
		node* n=q.front();
		q.pop();
		cout<<n->data<<" ";
		if(!n->lchild){
			n->lchild.layer=n.layer+1;
			q.emplace(n->lchild);
		}
		if(!n->rchild){
			n->rchild.layer=n.layer+1;
			q.emplace(n->rchild);
		}
	}
	return ;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务