根据先序和中序重建二叉树

//当前先序序列区间为[preL,preR],中序序列区间为[inL,inR],返回根节点 
node* create(int preL,int preR,int inL,int inR){
	if(preL>preR){
		return NULL;//先序序列长度小于等于0.直接返回为空 
	}
	node* root=new node;//新建一个新的结点,用来存放当前二叉树的根节点
	root->data=pre[preL];//新结点的数据域为根结点的值
	int k;
	for(k=inL;k<inR;k++){
		if(in[k]==pre[preL]){//在中序序列中找到In[k]==pre[L]的结点 
			break;
		}
	}
	int numLeft=k-inL;//左子树的结点个数,k是根在的位置 
	root->lchild=create(preL+1,preL+numLeft,inL,k-1);
	root->rchild=create(preL+numLeft+1,preR,k+1,inR);
	
	//左子树的先序区间(pre+1,pre+numLeft),中序区间为[inL,k-1]
	//返回左子树的根节点地址,赋值给root的左指针
	//右子树的先序区间为[preL+numLeft+1,preR],中序区间为[k+1,inR]
	//返回右子树的根节点地址,赋值给root的右指针
	return root; 
}	

你可能感兴趣的:(算法,二叉树,pat)