请在 下方输入 要搜索的题目:

树的遍历给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。输入格式:输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。

树的遍历给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。输入格式:输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。

发布时间:2025-06-24 16:15:57
推荐参考答案 ( 由 快搜搜题库 官方老师解答 )
联系客服
答案:#include<iostream>#include<algorithm>#include<cstring>#include<map>#include<queue> using namespace std; int inorder40];Int last40];Map<int,int> mp;Int n; struct node{ int val; node*left; node*right; node(int v):val(v),left(NULL),right(NULL){ }};Struct node* construct(int in],int inl,int inr,int last],int lastl,int lastr){ if(inl>inr) return NULL; int rootval=lastlastr]; struct node*root=new struct node(rootval); int index=mprootval]; root->left=construct(in,inl,index-1,last,lastl,lastl+index-1-inl); root->right=construct(in,index+1,inr,last,lastl+index-inl,lastr-1); return root;} void bfs(struct node*root){ queue<struct node*>q; q.push(root); while(q.size()) { auto t=q.front(); q.pop(); if(t->left) { q.push(t->left); } if(t->right) { q.push(t->right); } if(q.size()>=1) { cout<<t->val<<" "; } else{ cout<<t->val; } }} int main(){ cin>>n; for(int i=0; i<n; i++) { cin>>lasti]; } for(int i=0; i<n; i++) { cin>>inorderi]; mpinorderi]]=i; } struct node*root=construct(inorder,0,n-1,last,0,n-1); bfs(root);}
专业技术学习
专业技术学习
搜搜题库系统