重建二叉樹
題目:輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{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;
}