(先序遍历 后序遍历 中序遍历)三选二构造树

一.

先序遍历+中序遍历 以后序输出。



//由先序序列定义,此序列的第一个结点一定是二叉树的根。在中序序列里,此根结点左边的结点都是左子树的结点,而右边的结点都是右子树的结点。这样通过根结点,在中序序列中可以分离出:左子树的序列和右子树的序列。根据这两个序列,在先序序列中可以找到对应的左子序列和右子序列。在先序序列里左子序列的第一个结点是左子树的根,右子序列的第一个结点是右子树的根,这样就确定了二叉树的三个结点。同时,左右子树的根结点又可以分别把左右子序列划分成两个子序列。如此递归,当取尽先序序列中的结点时,就生成了一棵二叉树。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Node 
{
	union
	{
		char chData;
		int iData;
	}Data;
	Node *pLeft;
	Node *pRight;
};

Node* create(char *pPre, char *pIn, int iPre, int iInBegin, int iInEnd)
{
	static int temp = iPre;
	if (iInBegin >= iInEnd)
	{
		return NULL;
	}
	Node* root = new Node;
	if (!root)
	{
		exit(1);
	}
	root->Data.chData = pPre[iPre];
	root->pLeft = NULL;
	root->pRight = NULL;
	int i;
	for (i = iInBegin; i < iInEnd; i++)
	{
		if (pIn[i] == pPre[iPre])   //在中序序列中找到根节点的值
		{
			break;
		}
	}
	temp++;
	root->pLeft = create(pPre, pIn, temp, iInBegin, i);   //创建左子树
	root->pRight = create(pPre, pIn, temp, i+1, iInEnd);   //右子树
	return root;
}


void postorder(Node* root)
{


if(root->pLeft)postorder(root->pLeft);
if(root->pRight)postorder(root->pRight);
printf("%c",root->Data.chData);

}



int main()
{

char pPre[10]="DBACEGF",pIn[10]="ABCDEFG";
int len;

Node* root;
len=strlen(pPre);
root=create(pPre,pIn,0,0,len);

postorder(root);

return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值