链接:https://www.nowcoder.com/questionTerminal/8a19cbe657394eeaac2f6ea9b0f6fcf6
来源:牛客网

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

 

1、前序pre构建root节点

2、在中序vin中找到root节点,

3、root分割左右部分,分别进行递归构建。

 

struct TreeNode{
	int val;
	TreeNode * left;
	TreeNode* right;
	TreeNode(int x) :val(x), left(NULL), right(NULL) {}
};



TreeNode* reConstructBinaryTree1(vector<int> vin, int vb, int ve, vector<int> pre, int pb, int pe) {
	//子节点为空
	if (pb > pe)	return NULL;

	//创建节点
	TreeNode  *p = new TreeNode(pre[pb]);

	//找到p在中序vin的位置
	int cout = vb;
	while (p->val != vin[cout])
		cout++;

	//子序列宽度
	int len = cout - vb;

	//构建左子树,vin前半部分,pre前半部分
	p->left = reConstructBinaryTree1(vin, vb, cout - 1, pre, pb + 1, pb+ len);

	//构建右子树,vin后半部分,pre后半部分
	p->right = reConstructBinaryTree1(vin, cout + 1, ve, pre, pb + len +1, pe);

	return p;
}



TreeNode* reConstructBinaryTree(vector<int> pre, vector<int> vin) {
	return reConstructBinaryTree1(vin, 0, vin.size() -1, pre, 0, pre.size()-1);
}