1935 二叉树重建

定义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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值