L2-006. 树的遍历

来源:互联网 发布:office办公软件价格 编辑:程序博客网 时间:2024/06/10 19:14

L2-006. 树的遍历

时间限制
400 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越

给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。

输入格式:

输入第一行给出一个正整数N(<=30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。

输出格式:

在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。

输入样例:
72 3 1 5 7 6 41 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2

提交代码

解题思路:

不管是左右子树还是整棵树,后序遍历的最后一个元素就是根节点,然后从中序遍历中找到根节点在中序遍历的位置,并且记录左子树元素的个数。

中序遍历中根节点以前的位左子树,以后的位右子树,然后递归遍建立左右子树,如果子树为空则返回0,l>r的情况就是子树为空的情况。在根据根节点输出层序遍历就可以了。

#include<iostream>#include<cstdio>#include<cstring>#include<queue>using namespace std;#define N 35int last[N],in[N];struct node{int left;int right;}tree[N];int n,cnt;int build(int l1,int r1,int l2,int r2){int root;if(l1 <= r1&&l2 <= r2){root = last[r2];int cnt  = 0;int index;for(index = l1;in[index] != root;index++,cnt++);//判定根节点下标和确定左子树的元素个数 tree[root].left = build(l1,index-1,l2,l2+cnt-1);//建立左子树 tree[root].right = build(index+1,r1,l2+cnt,r2-1);//建立右子树 }else{return 0;}return root;}void print(int root){queue<int>q;q.push(root);//根节点入队 while(!q.empty()){int temp = q.front();cnt++;printf("%d",temp);//输出结点 if(cnt != n){printf(" ");}else{printf("\n");}q.pop();if(tree[temp].left){q.push(tree[temp].left);//左子树如队列 }if(tree[temp].right){q.push(tree[temp].right);//右子树入队列 }}}int main(){//freopen("input.txt","r",stdin);scanf("%d",&n);for(int i = 1;i <= n;i++){scanf("%d",&last[i]);}for(int i = 1;i <= n;i++){scanf("%d",&in[i]);}int root = build(1,n,1,n);print(root);return 0;} 


原创粉丝点击