由前序遍历序列和中序遍历序列重建二叉树


#include "iostream"
using namespace std;

typedef char ELEM_TYPE;
typedef  unsigned char INT8U;
typedef  unsigned short int INT16U;

typedef struct	BiTNode
	{
	    ELEM_TYPE	data;
	    struct BiTNode *lchild;
	    struct BiTNode *rchild;	
	}Node,*pNode;

pNode rebulid(ELEM_TYPE* pre_str,ELEM_TYPE* in_str,INT16U node_num);//pPRoot 根节点的地址的地址
void PostOrderTraverse(pNode pRoot);

int main(void)
{
	pNode pRoot = rebulid("ABCEDFGH","ECBDAGFH",8);
	PostOrderTraverse(pRoot);
	return 0;
}
int get_root_pos(ELEM_TYPE* str,ELEM_TYPE ch)
{
	int pos = 0;
	while(ch!=*str && '\0'!=*str)
	{
		str++;
		pos++; 
	}
	if('\0'==*str)
		return -1;
	else
		return pos;
}
pNode rebulid(ELEM_TYPE* pre_str,ELEM_TYPE* in_str,INT16U node_num)
{
	pNode pRoot = new Node;

	if(NULL==pRoot || 0==node_num)
	{
		return NULL;
	}
	else
	{
		INT16U root_pos = get_root_pos(in_str,pre_str[0]);					//得到根节点在中序遍历中的位置
		pRoot->data = pre_str[0];	
		if(root_pos >= node_num-1)
		{
			pRoot->rchild = NULL; 							
		}
		if(0 == root_pos)
		{
			pRoot->lchild = NULL; 
		}
		pRoot->lchild = rebulid(&pre_str[1],&in_str[0],root_pos);			
		pRoot->rchild = rebulid(&pre_str[root_pos+1],&in_str[root_pos+1],node_num-root_pos-1);
		return pRoot;
	}

}
void PostOrderTraverse(pNode pRoot)
{
	if(NULL == pRoot)
	{
		return;
	}
	else
	{
		PostOrderTraverse(pRoot->lchild);
		PostOrderTraverse(pRoot->rchild);
		cout<<pRoot->data;
	}
}


树的前序遍历:ABCEDFGH

树的中序遍历:ECBDAGFH

程序运行结果:树的后序遍历见下图

猜你喜欢

转载自blog.csdn.net/zhuangyongkang/article/details/41967231