上方是函数//定义二叉树链式结构typedef struct BitNode{char>数据结构与算法课程设计 起码硬币疑问
Source//code c++ 调试环境 vc++ 6.0//代码成功:#include
另外举一个例子,前序abecfg和中序beafcg。
前序先遍历根,故a为根,所以中序的be和fcg区分为左子树和右子树,前序对应是be和cfg,而后对左右子树用递归,很便捷的:struct Btree *tree(char *front,char *middle, int length)//middle为中序遍历的字符串,front为前序遍历的字符串。
//length为字符串长度。
struct Btree *root,//root为待建树的根结点{int position;if(length>0){root=(struct Btree *)malloc(sizeof(Btree));root->data=front[0];//middle[0]是根if(length!=1){//假设等于1,则曾经成功该子树构建,否则须要递归构建左和右子树。
position=find(middle,front[0];//找到根在前序遍历中的位置,字符串第一个字符从零开局计算。
root->lchild=tree(front+1,middle,position);//中序遍历的左子树在根前面,而前序遍历则在根前,就是最前面,这个递归就可以结构左子树。
留意子树对应的字符串长度增加了。
root->rchild=tree(front+position,middle+positon+1,length-position-1);//结构右子树。
}else{root->lchild=null;root->rchild=null; }//已成功构建,设置左右子树为空else root=null;//长度为零,说明该子树不存在,所以间接设置为空。
return(null);}