常用数据结构————树

关于树的考察点:二叉树的深度、树的子结构、二叉树中和为某一值得路径、重建二叉树、二叉树的后序遍历序列。

二叉搜索树:树种两个结点的最低公共祖先、二叉树与双向链表


重建二叉树:

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}。


typedef struct BinaryTreeNode{
	int key;
	BinaryTreeNode* left;
	BinaryTreeNode* right;
}	treenode;

treenode* construct(int* preoder,int* inorder,int length){

	if(preoder == NULL || inorder==NULL || length<=0){
		return NULL;
	}
	return construct_core(preoder,preoder+length-1,inorder,inorder+length-1);
}

treenode* construct_core(int* startprorder,int* endpreoreder,int* startinorder,int* endpinorder){
	//创建根节点,从前序遍历中找到树的根节点
	int rootvalue=startprorder[0];
	treenode* root = (treenode*) malloc(sizeof(treenode));
	root->key =rootvalue;
	root->left=NULL;
	root->right=NULL;

	//如果此时就一个值的话
	if(startprorder == endpreoreder){
		if(startinorder == endpinorder && *startinorder==*startprorder)
			return root;
		else{
			printf("所提供的数组值有问题!\n");
			return NULL;
		}
	}
	//将指针指向中序遍历的起始点
	int* rootinorder = startinorder;
	//开始遍历找到中序遍历的根节点所在的位置,搜索的情况是搜索不要超过原来搜索的数组长度,且值要找到相等的
	while(*rootinorder!=rootvalue && rootinorder<=endpinorder){
		rootinorder++;
	}

	if(rootinorder == endpinorder && *rootinorder != rootvalue){
		printf("搜提供的数组值有问题!\n");
		return NULL;
	}
	//算出左右子树的大小
	int leftlength = rootinorder - startinorder;
	int* left_preorder_end = startprorder + leftlength;//前序遍历中左子树结束的位置
	//构建左子树,如果还有子节点则继续递归构建子树
	if(leftlength>0){
		root->left = construct_core(startprorder+1,left_preorder_end,startinorder,rootinorder-1);
	}
	//构建右子树,如果右侧还有子节点则继续递归构建子树
	if(leftlength< endpreoreder - startprorder){
		root->right = construct_core(left_preorder_end+1,endpreoreder,rootinorder+1,endpinorder);
	}
	return root;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值