二叉树的建立

一:利用字符"#"作为结点左右孩子不存在的标记,有以下俩种方法

<1>scanf逐个输入字符串的情况:

BtNode * CreateTree1()
{
	BtNode *s = NULL;
	ElemType item;
	scanf("%c",&item);
	if(item != '#')
	{
		s = Buynode();
		s->data = item;
		s->leftchild = CreateTree1();
		s->rightchild = CreateTree1();
	}
	return s;
}
<2>字符串中包含字符"#"的情况:

BtNode * CreateTree2(char *&str)
{
	BtNode *s = NULL;
	if(str != NULL && *str != '#')
	{
		s = Buynode();
		s->data = *str;
		s->leftchild = CreateTree2(++str);
		s->rightchild = CreateTree2(++str);
	}
	return s;
}
二:根据前序遍历和中序遍历建立二叉树

例://char *ps = “ABCDEFGH”; char *is = “CBEDFAGH”;

int FindIs(char *is,int n,ElemType x)//用来找到中序遍历中根结点的位置
{
	for(int i = 0;i 0)
	{
		s = Buynode();
		s->data = ps[0];//前序遍历的第一个值为二叉树的根结点
		int pos = FindIs(is,n,ps[0]);
		if(pos == -1) exit(1);
		s->leftchild = Create(ps+1,is,pos);//将中序遍历后的根结点左右俩边分为左右子树
		s->rightchild = Create(ps+pos+1,is+pos+1,n-pos-1);
	}
	return s;
}
三:根据中序遍历和后序遍历建立二叉树
int FindIs(char *is,int n,ElemType x)//找到根结点在中序遍历的位置
{
	for(int i = 0;i 0)           //
	{
		int pos = FindIs(is,n,ls[n-1]);//切入点:后序遍历最后一个结点为二叉树的根结点
		if(pos == -1) exit(1);
		s = Buynode();
		s->data = ls[n-1];
		s->leftchild = Create2(is,ls,pos);
		s->rightchild = Create2(is+pos+1,ls+pos,n-pos-1);
	}
	return s;
}
BtNode * CreateIL(char *is,char *ls,int n)
{
	if(is == NULL || ls == NULL || n < 1)
		return NULL;
	else
		return Create2(is,ls,n);
}




你可能感兴趣的:(数据结构二叉树,二叉树,递归,建立)