一个前序遍历序列和一个中序遍历序列可以确定一颗唯一的二叉树。
根据前序遍历的特点, 知前序序列(PreSequence)的首个元素(PreSequence[0])为二叉树的根(root), 然后在中序序列(InSequence)中查找此根(root), 根据中序遍历特点, 知在查找到的根(root) 前边的序列为根的左子树的中序遍历序列, 后边的序列为根的右子树的中序遍历序列。 设在中序遍历序列(InSequence)根前边有left个元素. 则在前序序列(PreSequence)中, 紧跟着根(root)的left个元素序列(即PreSequence[1...left]) 为根的左子树的前序遍历序列, 在后边的为根的右子树的前序遍历序列.而构造左子树问题其实跟构造整个二叉树问题一样,只是此时前序序列为PreSequence[1...left]), 中序序列为InSequence[0...left-1], 分别为原序列的子串, 构造右子树同样, 显然可以用递归方法解决。
二叉树的定义于下:
-
- typedef struct BiNode
- {
- char data;
- struct BiNode * lchild;
- struct BiNode * rchild;
- }BiNode, * BiTree;
由前序遍历序列和中序遍历序列确定一颗唯一的二叉树的算法余下:
-
- void CreateBiTree(BiTree & t,string presequence,string insequence)
- {
- if(presequence.length()==0)
- {
- t=NULL;
- return ;
- }
- char rootNode=presequence[0];
- int index=insequence.find(rootNode);
- string lchild_insequence=insequence.substr(0,index);
- string rchild_insequence=insequence.substr(index+1);
- int lchild_length=lchild_insequence.length();
- int rchild_length=rchild_insequence.length();
- string lchild_presequence=presequence.substr(1,lchild_length);
- string rchild_presequence=presequence.substr(1+lchild_length);
-
- t=(BiTree)malloc(sizeof(BiNode));
- if(t!=NULL)
- {
- t->data=rootNode;
- CreateBiTree(t->lchild,lchild_presequence,lchild_insequence);
- CreateBiTree(t->rchild,rchild_presequence,rchild_insequence);
- }
- }