#include <iostream> using namespace std; struct node{ char data; node* lchild; node* rchild; }; //给定一棵二叉树的先序遍历序列和中序遍历序列,重建这棵二叉树 char pre[] = {‘A‘, ‘B‘, ‘D‘, ‘E‘, ‘C‘, ‘F‘}; //先序遍历序列 char in[]={‘D‘, ‘B‘, ‘E‘, ‘A‘, ‘F‘, ‘C‘}; //中序遍历序列 //当前先序序列区间为[preL, preR],中间序列区间为[inL, inR],返回根节点地址 node* create(int preL, int preR, int inL, int inR){ if(preL > preR){ return NULL; //先序序列长度小于等于0时,直接返回 } node* root = new node; //新建一个新节点,用来存放当前二叉树的根节点 root->data = pre[preL]; //新节点的数据域为根节点的值 int k; for(k = inL; k <= inR; k++){ if(in[k] == pre[preL]){ //在中序序列中找到in[k] == pre[L]的结点 break; } } int numLeft = k - inL; //左子树的结点个数 //左子树的先序区间为[preL+1, preL+numLeft],中序区间为[inL, k-1] //返回左子树的根节点地址,赋值给root的左指针 root->lchild = create(preL+1, preL+numLeft, inL, k-1); //右子树的先序区间为[preL+numLeft+1, preR],中序区间为[k+1, inR] //返回右子树的根节点地址,赋值给root的右指针 root->rchild = create(preL+numLeft+1, preR, k+1, inR); return root; } void preorder(node* root){ //先序遍历重建的树 if(root == NULL){ return; //到达空树,递归边界 } //访问根节点root,例如将其数据域输出 printf("%c\n", root->data); preorder(root->lchild); preorder(root->rchild); } int main() { node* root = new node; root = create(0,5,0,5); preorder(root); return 0; }