1020. Tree Traversals (25) @ PAT (Advanced Level) Practise

20 篇文章 0 订阅


思路:

对后序遍历结果从后向前进行遍历,其中每个值都是一个子树的根节点。用findNode(我用前序遍历)在tree中找到这个Node,将这个Node内的向量vct(中序遍历信息)拆分成左和右子树。

例:

Sample Input:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2


#include<iostream>
#include<vector>

using namespace std;
struct Node
{
	
	int value;
	vector<int> vct;//
	Node * lNode;//leftNode
	Node * rNode;//rightNode
	Node(int _value):value(_value),lNode(NULL),rNode(NULL){}//no use
	Node():value(0),lNode(NULL),rNode(NULL){}
};
vector<int> PO;//postOrder
struct Node tree;//root node
Node * findNode(int n,Node * s)
	//post Traversal the tree and scan the vector vct of the node
	//n - looking for;s -  start node
{
	Node * np;//node pointer
	if((*s).value!=0)
	{
		if(s->rNode!=NULL)
		{
			if((np=findNode(n,(*s).rNode))!=NULL)
			{
				return np;
			}
		}
		if(s->lNode!=NULL)
		{
			if((np=findNode(n,(*s).lNode))!=NULL)
			{
				return np;		
			}
		}
		
		return NULL;
	}
	else
	{
		vector<int>::iterator it;
		for(it=s->vct.begin();it!=s->vct.end();it++)
		{
			if((*it)==n)
			{
				return s;
			}
		}
		return NULL;
	}


	return np;
}
int main()
{
	//initialize & read data
	int N;
	cin>>N;	
	PO.resize(N);
	for(int i=0;i<N;i++)
		cin>>PO[i];
	int tmp;
	for(int i=0;i<N;i++)
	{
		cin>>tmp;
		tree.vct.push_back(tmp);
	}
	tree.value=0;
	//generate the tree
	vector<int>::reverse_iterator rit;
	Node * np;
	for(rit=PO.rbegin();rit!=PO.rend();rit++)
	{
		np=findNode(*rit,&tree);
		(*np).value=*rit;
		bool pushToLeft=true;
		vector<int> ::iterator it;
		for(it=(*np).vct.begin();it!=(*np).vct.end();it++)
		{
			if(*it == *rit)
			{
				pushToLeft=false;
				continue;
			}
			else
			{
				if(pushToLeft)
				{
					if((*np).lNode==NULL)
						(*np).lNode=new Node();
					(*np).lNode->vct.push_back(*it);
				}
				else
				{
					if((*np).rNode==NULL)
						(*np).rNode=new Node();
					(*np).rNode->vct.push_back(*it);
				}
			}
		}
	}
	//output level order
	vector<Node *> v1,v2;
	vector<int > result;
	v1.push_back(&tree);
	while(!v1.empty())
	{
		for(int i=0;i<v1.size();i++)
		{
			result.push_back(v1[i]->value);
			if(v1[i]->lNode!=NULL)
				v2.push_back(v1[i]->lNode);
			if(v1[i]->rNode!=NULL)
				v2.push_back(v1[i]->rNode);
		}
		v1.clear();
		v1.assign(v2.begin(),v2.end());
		v2.clear();
	}
	for(int i=0;i<result.size()-1;i++)
		cout<<result[i]<<" ";
	cout<<result[result.size()-1];
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值