构造二叉树(前序+中序&&中序+后序)

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

typedef struct BiTNode {
	char data;
	struct BiTNode *left;
	struct BiTNode *right;
}BiTNode,*BiTree;
//在中序遍历中找到根节点的位置
int find(char root_data,char *inOrder,int in_start,int in_end) {
	for (int i = in_start; i <= in_end; i++)
		if (inOrder[i] == root_data)
			return i;
}
//根据前序遍历和中序遍历构造二叉树
BiTree buildTree1(char *preOrder,int pre_start,int pre_end,char *inOrder,int in_start,int in_end) {
	if (in_start > in_end)
		return NULL;
		
	BiTree root = (BiTree)malloc(sizeof(BiTNode));
	root->data = preOrder[pre_start];
	root->left = NULL;
	root->right = NULL;
	if (in_start == in_end)
		return root;
	else {
		int root_index = find(root->data, inOrder, in_start, in_end);
		root->left = buildTree1(preOrder, pre_start + 1, pre_start + root_index - in_start, inOrder, in_start, root_index - 1);
		root->right = buildTree1(preOrder, pre_start + root_index - in_start + 1, pre_end, inOrder, root_index + 1, in_end);
		return root;
	}
}
//根据后序遍历和中序遍历构造二叉树
BiTree buildTree2(char *inOrder,int in_start,int in_end,char *postOrder,int post_start,int post_end) {
	if (in_start > in_end)
		return NULL;

	BiTree root = (BiTree)malloc(sizeof(BiTNode));
	root->data = postOrder[post_end];
	root->left = NULL;
	root->right = NULL;
	if (in_start == in_end)
		return root;
	else {
		int root_index = find(root->data, inOrder, in_start, in_end);
		root->left = buildTree2(inOrder, in_start, root_index - 1, postOrder, post_start, post_start + root_index - in_start - 1);
		root->right = buildTree2(inOrder, root_index + 1, in_end, postOrder, post_start + root_index - in_start, post_end - 1);
		return root;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值