1. 程式人生 > >二叉連結串列查詢

二叉連結串列查詢

二叉連結串列查詢

Problem Description
有一棵二叉樹,其結點值為字元型並假設各值互不相等,採用二叉連結串列儲存。現輸入其擴充套件二叉樹的前序遍歷序列,建立該二叉樹,要求在該二叉樹中查詢字元值為x的結點,找到x時,輸出x的相關資訊,沒找到x則輸出"not find"。
Input
第一行為一個整數n,表示以下有n組資料,每組資料佔兩行,每組第一行表示擴充套件二叉樹的前序遍歷序列;第二行表示待查詢的字元x。
Output
若查詢成功,先輸出該結點的雙親值,再輸出其左右孩子值:(左孩子,右孩子),若其雙親或者孩子值為空輸出#;查詢失敗輸出“not find”。

Sample Input


4
AB#D##C##
A
AB#D##C##
B
AB#D##C##
D
AB#D##C##
G
Sample Output
#(B,C)
A(#,D)
B(#,#)
not find
參考程式碼1:

#include<iostream>
using namespace std;
struct BiNode
{
	char data;
	BiNode *r,*l,*p;
};
BiNode *creat()
{
	char ch;
	cin>>ch;
	BiNode *root=NULL;
	if(ch!='#')
	{
		root=new BiNode;
		root->data=ch;
		root->l=creat();
		root->r=creat();
	}
	return root;
}
BiNode *haizi(BiNode *root,char x)
{
	if(root)
	{
		if(root->data==x)
		{
			return root;
		}
		else
		{
			BiNode *bt=haizi(root->l,x);
			if(bt)
				return bt;
			else
			{
				return haizi(root->r,x);
			}
		}
	}
		else
			return NULL;
}
BiNode *parent(BiNode *root,char x)
{
	if(root)
	{
	if(root->l&&root->l->data==x||
	  root->r&&root->r->data==x)
	{
		return root;
	}
	else 
	{
		BiNode *bt=parent(root->l,x);
		if(bt)
			return bt;
		else
			return parent(root->r,x);
	}
	}
	else 
		return NULL;
}
int main()
{
	int n;char b;
	while(cin>>n)
	{
		while(n--)
		{
			BiNode *child,*par;
			BiNode *root=creat();
			cin>>b;
			par=parent(root,b);
			child=haizi(root,b);
			if(child)
			{
				if(par)
					cout<<par->data;
				else 
					cout<<"#";
				if(child->l)
					cout<<"("<<child->l->data<<",";
				else 
					cout<<"("<<"#"<<",";
				if(child->r)
					cout<<child->r->data<<")"<<endl;
				else
					cout<<"#)"<<endl;
			}
			else
				cout<<"not find"<<endl;
		}
	}
	return 0;
}

參考程式碼2(三叉連結串列):

#include<iostream>
using namespace std;
struct BiNode 
{
   char data;
   BiNode *lchild,
	   *rchild,*parent;
};
BiNode *creat()
{
	char ch;
	BiNode *bt=NULL;
	cin>>ch;
	if(ch!='#')
	{
		bt=new BiNode;
		bt->data=ch;
		bt->parent=NULL;
		bt->lchild=creat();
		if(bt->lchild)
		{
			bt->lchild->parent=bt;
		}
		bt->rchild=creat();
		if(bt->rchild)
		{
			bt->rchild->parent=bt;
		}
	}
	return bt;
}
void Release(BiNode *bt)
{
	if(bt)
	{
		Release(bt->lchild);
		Release(bt->rchild);
		delete bt;
	}
}
BiNode *Locate(BiNode *bt,char x)
{
	if(bt)
	{
		if(bt->data==x)
			return bt;
		BiNode *t=Locate(bt->lchild,x);
		if(t)
		{
          return t;
		}
		return Locate(bt->rchild,x);
	}
	else return NULL;
}
int main ()
{
    int n;
	char x;
	cin>>n;
	while(n--)
	{
       BiNode *t,*root=creat();
	   cin>>x;
	   t=Locate(root,x);
       if(t)
	   {
		   if(t->parent)
			   cout<<t->parent->data<<"(";
		   else
			   cout<<"#(";
		   if(t->lchild)
			   cout<<t->lchild->data<<",";
		   else
			   cout<<"#,";
		   if(t->rchild)
			   cout<<t->rchild->data<<")"<<endl;
		   else
			   cout<<"#)"<<endl;
	   }
	   else
		   cout<<"not find"<<endl;
	   Release(root);
	}
	return 0;
}