根据前序遍历序列和中序遍历序列构造二叉树算法

来源:互联网 发布:单片机c51简易数字钟 编辑:程序博客网 时间:2024/05/17 20:33

一个前序遍历序列和一个中序遍历序列可以确定一颗唯一的二叉树。

       根据前序遍历的特点, 知前序序列(PreSequence)的首个元素(PreSequence[0])为二叉树的根(root),  然后在中序序列(InSequence)中查找此根(root),  根据中序遍历特点, 知在查找到的根(root) 前边的序列为根的左子树的中序遍历序列,  后边的序列为根的右子树的中序遍历序列。 设在中序遍历序列(InSequence)根前边有left个元素. 则在前序序列(PreSequence)中, 紧跟着根(root)的left个元素序列(即PreSequence[1...left]) 为根的左子树的前序遍历序列, 在后边的为根的右子树的前序遍历序列.而构造左子树问题其实跟构造整个二叉树问题一样,只是此时前序序列为PreSequence[1...left]), 中序序列为InSequence[0...left-1], 分别为原序列的子串, 构造右子树同样, 显然可以用递归方法解决。

 二叉树的定义于下:

[cpp] view plain copy
  1. //二叉链表表示二叉树  
  2. typedef struct BiNode  
  3. {  
  4.     char data;//节点数据  
  5.     struct BiNode * lchild;//左孩子  
  6.     struct BiNode * rchild;//右孩子  
  7. }BiNode, * BiTree;  
 

前序遍历序列和中序遍历序列确定一颗唯一的二叉树的算法余下:

[cpp] view plain copy
  1. //由前序序列和中序序列建立二叉树的过程  
  2. void CreateBiTree(BiTree & t,string presequence,string insequence)//t为要建立的二叉树,presequence和insequence分别为前序和中序序列  
  3. {  
  4.    if(presequence.length()==0)  
  5.    {  
  6.          t=NULL;  
  7.          return ;  
  8.    }  
  9.    char rootNode=presequence[0];//根  
  10.    int index=insequence.find(rootNode);//根在中序序列中的位置  
  11.    string lchild_insequence=insequence.substr(0,index);//左孩子的中序序列  
  12.    string rchild_insequence=insequence.substr(index+1);//右孩子的中序序列  
  13.    int lchild_length=lchild_insequence.length();//左孩子的长度  
  14.    int rchild_length=rchild_insequence.length();//右孩子的长度  
  15.    string lchild_presequence=presequence.substr(1,lchild_length);//左孩子的前序序列  
  16.    string rchild_presequence=presequence.substr(1+lchild_length);//右孩子的前序序列  
  17.   
  18.    t=(BiTree)malloc(sizeof(BiNode));  
  19.    if(t!=NULL)  
  20.    {  
  21.        t->data=rootNode;  
  22.        CreateBiTree(t->lchild,lchild_presequence,lchild_insequence);//递归创建左孩子  
  23.        CreateBiTree(t->rchild,rchild_presequence,rchild_insequence);//递归创建右孩子  
  24.    }  
  25. }  

阅读全文
0 0