2489: 进击的二叉查找树 (二叉树的操作)


#include<stdio.h>
#include<queue>
#include<algorithm>
using namespace std;
	int n;
struct Node{
	int data;
	Node *lchild,*rchild;
	Node(int e):data(e),lchild(NULL),rchild(NULL){}
	
	
};
//二叉树插入 
	Node *  insert(Node *T,int num){
		if(T==NULL)
		return new Node(num);
		if(num<T->data) T->lchild=insert(T->lchild,num);
		else T->rchild=insert(T->rchild,num);
		return  T;
	}
//判断两个二叉树是否相同 
int judge(Node *r,Node *r1){
	if(!r&&!r1)
	return 1;
	else if(r&&r1){
		if(r->data==r1->data)
		return judge(r->lchild,r1->lchild)&&judge(r->rchild,r1->rchild);
	}
	return 0;
}
//前序遍历 
void postra(Node *r,int &w)
{
    if(r){
        postra(r->lchild,w);
        postra(r->rchild,w);
        ++w==n?printf("%d\n",r->data):printf("%d ",r->data);
    }
}
//层序遍历 
void levtra(Node *r)
{
    queue<Node *> q;
    q.push(r);
    int w=0;
    while(!q.empty())
    {
        Node *s=q.front();
        q.pop();
        ++w==n?printf("%d\n",s->data):printf("%d ",s->data);
        if(s->lchild) q.push(s->lchild);
        if(s->rchild) q.push(s->rchild);
    }
}
//中序遍历 level为层数
void InOrderTraverse(Node* T,int level){
	if(T==NULL)
	return;
	InOrderTraverse(T->lchild,level+1);
	
	//operation1(T->data);
	printf("%d",T->data); 
	
	InOrderTraverse(T->rchild,level+1);
}
//后序遍历
void PostOrderTraverse(Node* T,int level)
{
	if(T==NULL)
	return;
	PostOrderTraverse(T->lchild,level+1);
	PostOrderTraverse(T->rchild,level+1);
	
	//operation1(T->data);
	printf("%d",T->data); 
}
int main(){
	freopen("in.txt","r",stdin);
	scanf("%d",&n);
	Node * root = NULL;
	
	for(int i=1;i<=n;i++){
		int e;
		scanf("%d",&e);
		root=insert(root,e);
	}
	Node * root1 = NULL;
	
	for(int i=1;i<=n;i++){
		int e;
		scanf("%d",&e);
		root1=insert(root1,e);
	}
	if(judge(root,root1)==1)
	printf("YES\n");
	else printf("NO\n");
	
	int w=0;
	postra(root,w);
	levtra(root);
	/*InOrderTraverse(root,0);
	puts("");
	PostOrderTraverse(root,0);*/
	return 0;
}

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页