PAT-1020 Tree Traversals (25 分)树的遍历

1020 Tree Traversals (25 分)

Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

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

题目大意: 第一行给出一个树的节点个数N,第二行给出该树后序遍历的结果,第三行给出该树中序遍历的结果,求该树的层序遍历(及按照从上到下从左到右,按层输出遍历结果)。输入的数是各不相同的

输出要求:每个数间隔一个空格,最后一个数后没有空格。

思路:后序遍历的最后一个值总是根节点,它可将中序遍历分为左右子树两部分,在根据中序的左右子树可在后续遍历中找到相应子树的根节点。由此循环往复,最终构建出一棵树。

子树与原树有相同结构  ,可用递归解决。

计数方法:

将根节点记为n,左儿子为2*n+1,右儿子为2*n+2。从零开始计数

坑点:1.输入的数不是连续的。

           2.不能只记录每个节点的层号  然后按层号进行排序输出 。原因:1.排序可能是不稳定的。2.光用层号无法定位该节点在               这一层的位置。

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct Node{             //节点
	int number;          //记录该节点的值
	int num;             //记录该节点在树中的位置
};
vector<Node>nodes;
void input(vector<int> &postorder,vector<int> &inorder){
	int n;
	cin>>n;
	postorder.resize(n);
	inorder.resize(n);
	for(int i=0;i<n;i++){
		cin>>postorder[i];
	}
	for(int i=0;i<n;i++){
		cin>>inorder[i];
	}
}
int compare(Node &a,Node &b){            //将节点按照位置由小到大排序
	return a.num<b.num;
}
void computeFloor(vector<int>&postorder,vector<int>&inorder,int ibegin,int iend,int pend,int num){                 //ibegin,iend 中序遍历数组的头和尾   pend 后续的尾(根节点)
	if(ibegin>iend){
		return ;
	}
	Node temp;
	temp.number=postorder[pend];
	temp.num=num;
	nodes.push_back(temp);      //记录并保存该节点的信息

	int i=ibegin;
	for(;i<=iend;i++){   //找到该根节点在中序的位置,将中序分为左右子树
		if(inorder[i]==postorder[pend])
			break;
	}

	computeFloor(postorder,inorder,ibegin,i-1,pend-1-(iend-i),num*2+1);
	computeFloor(postorder,inorder,i+1,iend,pend-1,num*2+2);

}
int main(){
	vector<int>postorder;
	vector<int>inorder;
	input(postorder,inorder);
	computeFloor(postorder,inorder,0,inorder.size()-1,postorder.size()-1,0);
	sort(nodes.begin(),nodes.end(),compare);
	for(int i=0;i<nodes.size()-1;i++){
		cout<<nodes[i].number<<" ";
	}
	cout<<nodes.back().number<<endl;
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值