重建二叉树
题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建出如下图所示的二叉树并输出它的头结点。
输入:前序:{1,2,4,7,3,5,6,8}和中序{4,7,2,1,5,3,8,6}
输出:重建的二叉树根节点
思路:1、首先使用递归的思想,每次只构建一个树的节点并返回
2、对于该节点的值直接取前序数组的第一个元素,然后在中序数组中找出该节点的值所在的位置,比如”1”在中序的第3个位置(数组从0开始编号)
3、如果该节点在中序所占的位置3中,左边还有元素,则进一步将左边的元素存入前序数组中,然后构建左子树。比如前序{2,4,7},中序{4,7,2}构建左子树
4、如果该节点在中序所占的位置3中,右边还有元素,则进一步将右边的元素存入前序数组中,然后构建右子树。比如前序{3,5,6,8},中序{5,3,8,6}构建右子树
5、如果左边没有元素,则左子树为空,反之,则右子树为空
/*
实现:重建二叉树
*/
#include<iostream>
#include<vector>
using namespace std;
struct BinaryTreeNode{
int value;
BinaryTreeNode *left;
BinaryTreeNode *right;
};
BinaryTreeNode* ConstructTree(int *startPreorder, int *endPreorder, int *startInorder, int *endInorder){
BinaryTreeNode* root = new BinaryTreeNode();
root->value = startPreorder[0];
root->left = root->right = NULL;
//下面对该点进行判断,如果前序序列只有该点这么一个点
if (startPreorder == endPreorder){
if (startInorder == endInorder && *startPreorder == *startInorder){
return root;
}
else{
cout << "error" << endl;
return NULL;
}
}
//下面查找startInorder~endInorder之间的该值startPreorder[0]的位置,然后迭代的去找左右子树
int i = 0;
while (startInorder[i] != endInorder[0]){
if (startInorder[i] == startPreorder[0]){
break;
}
i++;
}
if (startInorder + i - 1 <= endInorder && i >= 1){
root->left = ConstructTree(startPreorder + 1, startPreorder + i, startInorder, startInorder + i - 1);
}
if (startInorder + i + 1 <= endInorder && startPreorder + i + 1 <= endPreorder){
root->right= ConstructTree(startPreorder + i + 1, endPreorder, startInorder+i+1, endInorder);
}
return root;
}
BinaryTreeNode* Construct(int *preorder, int *inorder, int length){
if (length < 1 || preorder == NULL || inorder==NULL){
return NULL;
}
ConstructTree(preorder, preorder + length - 1, inorder, inorder + length - 1);
}
void Print(BinaryTreeNode* pRoot){
if (pRoot->left != NULL){
Print(pRoot->left);
}
cout << pRoot->value << " ";
if (pRoot->right != NULL){
Print(pRoot->right);
}
}
int main(){
int preorder[] = { 1, 2, 4, 7, 3, 5, 6, 8 };
int inorder[] = { 4, 7, 2, 1, 5, 3, 8, 6 };
int length = 8;
BinaryTreeNode *pRoot = Construct(preorder, inorder,length);
Print(pRoot);
system("pause");
return 0;
}