1020. Tree Traversals (25)
来源:互联网 发布:梯度下降算法迭代 编辑:程序博客网 时间:2024/06/08 19:44
- 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
#include<stdio.h>#include<stdlib.h>typedef struct TreeNode* BinTree;struct TreeNode{ int data; BinTree left,right;};BinTree build(int* post,int* in,int n){//有后序遍历和中序遍历,构造二叉树 BinTree root; if(!n) return NULL; root=malloc(sizeof(struct TreeNode)); root->data=post[n-1]; int i; for(i=0;i<n;i++){ if(post[n-1]==in[i]) break; } root->left=build(post,in,i); root->right=build(post+i,in+i+1,n-1-i); return root;}void bfs(BinTree root,int n,int ans[]){//对二叉树进行宽度优先遍历 int front=0,rear=1; BinTree q[n]; q[0]=root; int i=0; while(front<rear){ BinTree u=q[front++]; ans[i++]=u->data; if(u->left) q[rear++]=u->left; if(u->right) q[rear++]=u->right; }}void remove_tree(BinTree root){ if(root==NULL) return; remove_tree(root->left); remove_tree(root->right); free(root);}int main(){ int N; scanf("%d",&N); int post[N],in[N],ans[N]; int i; for(i=0;i<N;i++){ scanf("%d",&post[i]); } for(i=0;i<N;i++){ scanf("%d",&in[i]); } BinTree root=build(post,in,N); bfs(root,N,ans); remove_tree(root); for(i=0;i<N;i++){ if(i) printf(" %d",ans[i]); else printf("%d",ans[i]); } return 0; }
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- java类成员初始化顺序
- Fibonacci法的matlab实现
- Android中的通知notification
- Spring集成Junit4单元测试
- C++
- 1020. Tree Traversals (25)
- 求最大连续bit数
- 字符串 挑出 字符串
- 机器学习面临的挑战和解决方法
- Android中圆形图的几种实现方式
- 简单的排障 - load高
- 用nginx的反向代理机制解决前端跨域问题
- js 设置cookie和获取cookie
- Android开发之自定义圆形的ImageView的实现