1020. Tree Traversals (25)
Posted gaoren
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
题目大意:由二叉树的中序遍历和后序遍历求出层序遍历的结果。
#include<iostream> #include<stdio.h> #include<cstring> #include<queue> #include<stdlib.h> using namespace std; int N; #define max 40 int postorder[max]; int inorder[max]; int cnt; struct tree{ struct tree *left; struct tree *right; int num; }; int searchValue(int num){ int i; for(i=0;i<N;i++){ if(inorder[i]==num){ return i; } } return -1; } tree * createTree(int left, int right){ if(left > right)return NULL; int root = postorder[cnt]; cnt --; int rootChild = searchValue(root); tree* t= (tree*)malloc(sizeof(tree)); t->num = root; if(left == right){ t->left = NULL; t->right = NULL; } else{ t->right = createTree(rootChild+1,right); t->left = createTree(left,rootChild-1); //cout<<"hello world"<<endl; } return t; } void output(tree * t){ int levelorder[max]; queue<tree*>q_tree; q_tree.push(t); int i=0; levelorder[i++]=t->num; while(!q_tree.empty()){ tree* index = q_tree.front(); q_tree.pop(); if(index->left!=NULL){ q_tree.push(index->left); levelorder[i++]=index->left->num; } if(index->right!=NULL){ q_tree.push(index->right); levelorder[i++]=index->right->num; } } int j; for(j=0;j<i;j++){ if(j+1==i){ printf("%d\n",levelorder[j]); } else{ printf("%d ",levelorder[j]); } } } int main(){ scanf("%d",&N); int i,j; for(i=0;i<N;i++){ scanf("%d",&postorder[i]); } for(j=0;j<N;j++){ scanf("%d",&inorder[j]); } cnt = N-1; tree* tt=createTree(0,N-1); //cout<<"hello world"<<endl; output(tt); return 0; }
以上是关于1020. Tree Traversals (25)的主要内容,如果未能解决你的问题,请参考以下文章