版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_42449444/article/details/85331082
本题要求根据给定的一棵二叉树的后序遍历和中序遍历结果,输出该树的先序遍历结果。
第一行给出正整数N(≤30),是树中结点的个数。随后两行,每行给出N个整数,分别对应后序遍历和中序遍历结果,数字间以空格分隔。题目保证输入正确对应一棵二叉树。
在一行中输出Preorder:
以及该树的先序遍历结果。数字间有1个空格,行末不得有多余空格。
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Preorder: 4 1 3 2 6 5 7
1.先序遍历的递归过程为:若二叉树为空,遍历结束。否则:①访问根结点;②先序遍历根结点的左子树;③先序遍历根结点的右子树。 简单来说先序遍历就是在深入时遇到结点就访问。
2.中序遍历的递归过程为:若二叉树为空,遍历结束。否则:①中序遍历根结点的左子树;②访问根结点;③中序遍历根结点的右子树。简单来说中序遍历就是从左子树返回时遇到结点就访问。
3.后序遍历的递归过程为:若二叉树为空,遍历结束。否则:①后序遍历根结点的左子树;②后序遍历根结点的右子树;③访问根结点。简单来说后序遍历就是从右子树返回时遇到结点就访问。
#include <bits/stdc++.h>
using namespace std;
void getpre(int *postorder,int *inorder,int n) //其中数组postorder为后序,inorder为中序,n为每次遍历数目
{
if(n>0)
{
int root = postorder[n-1]; //根结点为后序遍历的最后一个
int i;
for(i = 0; i < n; i++) //在中序遍历中查找根结点
{
if(inorder[i] == root)
{
break;
}
}
cout << " " << root;
getpre(postorder, inorder, i); //对左子树来查找根结点
getpre(postorder+i, inorder+i+1, n-i-1); //对右子树来查找根结点
}
}
int main()
{
int n;
cin >> n;
int postorder[n],inorder[n]; //postorder[n]后序 inorder[n]中序
for(int i=0;i<n;i++)
{
cin >> postorder[i]; //输入后序
}
for(int i=0;i<n;i++)
{
cin >> inorder[i]; //输入中序
}
cout << "Preorder:";
getpre(postorder,inorder,n);
return 0;
}