其他分享
首页 > 其他分享> > 根据前中后序序列创建二叉树

根据前中后序序列创建二叉树

作者:互联网

已知前中后序创建二叉树

前序和中序创建二叉树

在这里插入图片描述

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
#include<stdbool.h>
#define ElemType char

typedef struct BinTreeNode
{
	ElemType data;
	struct BinTreeNode* leftChild;
	struct BinTreeNode* rightChild;
}BinTreeNode;

typedef BinTreeNode* BinTree;
BinTree BinTreeCreate_VLR_LVR(const char *vlr, const char* lvr,int n)
{
	if (n == 0)
		return NULL;
	int k = 0;
	while (lvr[k] != vlr[0])
		k++;
	BinTreeNode* t = (BinTreeNode*)malloc(sizeof(BinTreeNode));
	assert(t);
	t->data = lvr[k];

	t->leftChild = BinTreeCreate_VLR_LVR(vlr+1, lvr, k);
	t->rightChild = BinTreeCreate_VLR_LVR(vlr+k+1,lvr+k+1,n-k-1);

	return t;
}

test:

int main()
{
	BinTree bt = NULL;
	char* vlr = "ABCDEFGH";
	char* lvr = "CBEDFAGH";
	char* lrv = "CEFDBHGA";
	int n = strlen(vlr);
	bt = BinTreeCreate_VLR_LVR(vlr, lvr,n);
	return 0;
}

中序和后序创建二叉树

和上面的做法基本一样:首先根据后序序列找到根,再找到根所处中序序列的位置,然后先创建“右树”后创建“左树”

BinTree BinTreeCreate_LVR_LRV(const char* lvr, const char* lrv, int n)
{
	if (n == 0)
		return NULL;
	int k = 0;
	while (lvr[k] != lrv[n - 1])
		k++;
	BinTreeNode* t = (BinTreeNode*)malloc(sizeof(BinTreeNode));
	assert(t);
	t->data = lvr[k];
	t->rightChild = BinTreeCreate_LVR_LRV(lvr+k+1, lrv+k, n-k-1);
	t->leftChild = BinTreeCreate_LVR_LRV(lvr, lrv, k);
	return t;
}

前序和后序创建二叉树

已知前序和后序序列无法创建二叉树

标签:BinTreeCreate,lvr,前中,后序,char,二叉树,BinTreeNode
来源: https://blog.csdn.net/qq_43560037/article/details/113666501