当前位置:网站首页>由中序遍历和后序遍历得到前序遍历(树的遍历)
由中序遍历和后序遍历得到前序遍历(树的遍历)
2022-08-02 03:22:00 【寒江飞冰】
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树的前序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
4 1 3 2 6 5 7
#include<iostream>
using namespace std;
int a[31];
int b[31];
typedef struct Node{
int data;
Node *lchild;
Node *rchild;
}Node,*Tree;
Tree build(int *x,int *y,int n)
{
if(n<=0)
{
return NULL;
}
int *p=x;
while(p)
{
if(*p==*(y+n-1)) break;
p++;
}
Tree T = new Node;
T->data=*p;
int len=p-x;
T->lchild=build(x,y,len);
T->rchild=build(p+1,y+len,n-len-1);
return T;
}
void Print(Tree T)
{
if(T)
{
cout<<' '<<T->data;
Print(T->lchild);
Print(T->rchild);
}
}
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++) cin>>a[i];
for(int i=0;i<n;i++) cin>>b[i];
Tree T;
T=build(b,a,n);
Print(T);
}
边栏推荐
- Chapter 10 Clustering
- C语言 结构体定义方法
- 【深度学习】从LeNet-5识别手写数字入门深度学习
- ModuleNotFoundError No module named ‘xxx‘可能的解决方案大全
- C语言中关于2的n次方求值问题(移位运算)
- SOCKS5
- 科研试剂DMPE-PEG-Mal 二肉豆蔻酰磷脂酰乙醇胺-聚乙二醇-马来酰亚胺
- IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boo
- DSPE-PEG-Silane,DSPE-PEG-SIL,磷脂-聚乙二醇-硅烷修饰活性基团
- getattr() function analysis
猜你喜欢
随机推荐
Source Insight 使用教程(2)——常用功能
How to check whether a table is locked in mysql
debian 10 nat 与路由转发
getattr() function analysis
Chapter 10 Clustering
nucleo stm32 h743 FREERTOS CUBE MX配置小记录
Knowledge Engineering Assignment 2: Introduction to Knowledge Engineering Related Fields
化学试剂磷脂-聚乙二醇-羟基,DSPE-PEG-OH,DSPE-PEG-Hydroxyl,MW:5000
cross-domain problem solving
SOCKS5
【手把手带你学nRF52832/nRF52840 · (1)开发环境搭建】
Debian 10 NTP Service Configuration
DSPE-PEG-DBCO 磷脂-聚乙二醇-二苯并环辛炔 一种线性杂双官能聚乙二醇化试剂
知识工程作业2:知识工程相关领域介绍
COCO数据集训练TPH-YoloV5
【面经】米哈游数据开发一面二面面经
STM32 CAN过滤器
Redis simple study notes
A senior test engineer asked me these questions as soon as the interview came
排序学习笔记(二)堆排序









