- 基本理论
1.二叉树结点结构体:左右孩子指针&data
struct BTNode()
{
BTNode *lchild;
BTNode *rchild;
/**
其他信息
**/
};
2.递归遍历方法(eg.中序遍历)
void inOrder(BTNode *Tree)
{
if(Tree->lchild!=NULL)
inOrder(Tree->lchild);
/**
遍历当前结点
**/
if(Tree->rchild!=NULL)
inOrder(Tree->rchild);
return;
}
- 例1、给出二叉树前中序,输出后序。
思路:由前中序建立一棵二叉树,在读出后序。
结构体:
struct Node{
BTree *lchild;
BTree *rchild;
char c;
};
解题:
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
struct Node{
Node *lchild;
Node *rchild;
char c;
}Tree[50];//静态内存分配数组
int loc=0;//静态数组中已分配的数组个数
//申请一个结点空间,返回指向他的指针
Node *creat()
{
Tree[loc].lchild=Tree[loc].rchild=NULL;
return &Tree[loc++];
}
//保存前中序遍历字符
char str1[50],str2[50];
//后序遍历
void postOrder(Node *T)
{
if(T->lchild!=NULL)
postOrder(T->lchild);
if(T->rchild!=NULL)
postOrder(T->rchild);
cout<<T->c;
return;
}
//由前中序建立一棵二叉树,返回根节点
//前序遍历结果为由srt1[s1]到srt2[e1]
//中序遍历结果为由srt2[s2]到srt2[e2]
Node *build(int s1,int e1,int s2,int e2)
{
Node* ret=creat();//为树根结点申请空间
ret->c=str1[s1];//树根结点为前序遍历第一个字符
int rootIdx;//树根结点在中序遍历中的位置
//查找树根结点在中序遍历中的位置
for(int i=s2;i<=e2;i++)
{
if(str2[i]==ret->c)
{
rootIdx=i;
break;
}
}
//递归还原左子树
if(rootIdx!=s2)//左子树不为空
{
ret->lchild=build(s1+1,s1+(rootIdx-s2),s2,rootIdx-1);
}
//递归还原右子树
if(rootIdx!=e2)//右子树不为空
{
ret->rchild=build(s1+(rootIdx-s2)+1,e1,rootIdx+1,e2);
}
return ret;//返回根节点指针
}
int main(){
cin>>str1>>str2;
int len1=strlen(str1),len2=strlen(str2);
//还原整棵树,根节点指针保存在T中
Node *T=build(0,len1-1,0,len2-1);
//后序遍历
postOrder(T);
return 0;
}