二叉树基础
二叉树的概念、性质、遍历
二叉树遍历-前序遍历、中序遍历、后序遍历、层次遍历、深度优先、广度优先遍历
例题:
数据结构上机测试4.1:二叉树的遍历与应用1
Description
输入二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列。
Input
第一行输入二叉树的先序遍历序列;
第二行输入二叉树的中序遍历序列。
Output
输出该二叉树的后序遍历序列。
Sample
Input
ABDCEF
BDAECF
Output
DBEFCA
#include<bits/stdc++.h>
using namespace std;
const int N = 1010;
//#define N 1010
char pre[N],mid[N],post[N]; //前中后序遍历字符串
struct node
{
char data; //数值域
node *l,*r; //指针域
};
node *buildtree(int len,char *pre,char *mid) //建树
{
node *root;
if(!len) //判断树是否为空
{
return NULL;
}
root =new node;
root->data=pre[0]; //找根结点
int i;
for(i=0;i<len;i++) //找中序遍历中根结点所在位置
{
if(mid[i]==pre[0])
{
break;
}
}
root->l=buildtree(i,pre+1,mid); //建立左子树
root