创建树、先序遍历和中序遍历创建树、后序遍历和中序遍历创建树

BtNode * CreateTree1()
{
	BtNode *s = NULL;
	ElemType item;
	cin>>item;
	if(item != '#')
	{
		s = Buynode();
		s->data = item;
		s->leftchild = CreateTree1();
		s->rightchild = CreateTree1();
	}
	return s;
}
BtNode * CreateTree2(ElemType *&str)
{
	BtNode *s = NULL;
	if(NULL != str && *str != END)
	{
		s = Buynode();
		s->data = *str;
		s->leftchild = CreateTree2(++str);
		s->rightchild = CreateTree2(++str);
	}
	return s;
}

 

创建树、先序遍历和中序遍历创建树、后序遍历和中序遍历创建树_第1张图片创建树、先序遍历和中序遍历创建树、后序遍历和中序遍历创建树_第2张图片

先序遍历可以确定出树的根节点即第一个元素就是根节点,中序遍历可以确定左子树和右子树,接下来依次递归,直到区间的个数<=0就能确定出这棵树

 

BtNode * Buynode()
{
	BtNode *s = (BtNode*)malloc(sizeof(BtNode));
	if(NULL == s) exit(1);
	memset(s,0,sizeof(BtNode)); // new;
	return s;
}
int FindPos(ElemType *is,ElemType x,int n)
{
	int pos = -1;
	for(int i = 0;i 0)
	{
		s = Buynode();
		s->data = ps[0];
		int pos = FindPos(is,ps[0],n);
		if(pos == -1) exit(1);
		s->leftchild = CreatePI(ps+1,is,pos);
		s->rightchild = CreatePI(ps+pos+1,is+pos+1,n - pos - 1);
	}
	return s;
}
BtNode * CreateTreePI(ElemType *ps,ElemType *is,int n)
{
	if(NULL == ps || NULL == is || n < 1)
		return NULL;
	else
		return CreatePI(ps,is,n);
}

 

创建树、先序遍历和中序遍历创建树、后序遍历和中序遍历创建树_第3张图片

后续遍历可以确定出树的根节点即最后一个元素就是根节点,中序遍历可以确定左子树和右子树,接下来依次递归,直到区间的个数<=0就能确定出这棵树

BtNode * Buynode()
{
	BtNode *s = (BtNode*)malloc(sizeof(BtNode));
	if(NULL == s) exit(1);
	memset(s,0,sizeof(BtNode)); // new;
	return s;
}
int FindPos(ElemType *is,ElemType x,int n)
{
	int pos = -1;
	for(int i = 0;i 0)
	{
		s = Buynode();
		s->data = ls[n-1];
		int pos = FindPos(is,ls[n-1],n);
		if(pos == -1) exit(1);
		s->leftchild = CreateIL(is,ls,pos);
		s->rightchild = CreateIL(is+pos+1,ls+pos,n-pos-1);
	}
	return s;
}
BtNode * CreateTreeIL(ElemType *is,ElemType *ls,int n)
{
	if(NULL == is || NULL == ls || n < 1)
		return NULL;
	else
		return CreateIL(is,ls,n);
}

 

你可能感兴趣的:(知识点)