定义node
struct node{
char name;
node* lchild;
node* rchild;
};
bfs 广度遍历 树+ queue
void bfs()
{
que.push(roo);
while(!que.empty())
{
node *temp;
temp=que.front();
cout<<temp->name;
que.pop();
if(temp->lchild!=NULL)
que.push(temp->lchild);
if(temp->rchild!=NULL)
que.push(temp->rchild);
}
}
分治 递归:
void recur(node*&newnode ,int i,int j){
if(i>j) newnode=NULL;
else
{
char ch=s1[posi++];
int in=findch(ch);
newnode=new node;
newnode->name=s2[in];
recur(newnode->lchild,i,in-1);
recur(newnode->rchild,in+1,j);
}
}
someting new :
void function(Pointer*&pt)
meaning of *&
void recur(node*&newnode ,int i,int j)
{ //*stand for pointer(cause newnode is a pointer!!)& stand for reference(cause we wanna change the List!&使实参形参同一化)
完
#include<iostream>
#include<string>
#include<queue>
using namespace std;
string s1,s2;
struct node{
char name;
node* lchild;
node* rchild;
};
int posi;
node *roo;
queue<node*>que;
int findch(char ch)
{
int i=0;
for (; i < s2.length(); ++i)
{
if(s2[i]==ch)
break;
}
return i;
}
void bfs()
{
que.push(roo);
while(!que.empty())
{
node *temp;
temp=que.front();
cout<<temp->name;
que.pop();
if(temp->lchild!=NULL)
que.push(temp->lchild);
if(temp->rchild!=NULL)
que.push(temp->rchild);
}
}
void recur(node*&newnode ,int i,int j)
{ //*stand for pointer(cause newnode is a pointer!!)& stand for reference(cause we wanna change the List!&使实参形参同一化)
if(i>j) newnode=NULL;
else
{
char ch=s1[posi++];
int in=findch(ch);
newnode=new node;
newnode->name=s2[in];
recur(newnode->lchild,i,in-1);
recur(newnode->rchild,in+1,j);
}
}
int main()
{
int T;
cin>>T;
while(T--)
{
cin>>s1>>s2;
posi=0;
que=queue<node*>();
recur(roo,0,s1.length()-1);
bfs();
cout<<endl;
}
return 0;
}