关键点就是每个根结点的左子树和右子树都连在一块,所以只要找到根结点就能切割
#include <iostream>
#include <stdexcept>
#include <queue>
struct BinaryTreeNode {
int m_nValue;
BinaryTreeNode * leftChild;
BinaryTreeNode * rightChild;
};
BinaryTreeNode * constructorCore (int * startPreorder, int * endPreorder, int * startInorder, int * endInorder);
BinaryTreeNode * constructor (int * preorder, int * inorder, int length) {
if (preorder == NULL || inorder == NULL || length <= 0) {
return NULL;
}
return constructorCore(preorder, preorder + length - 1, inorder, inorder + length - 1);
}
BinaryTreeNode * constructorCore (int * startPreorder, int * endPreorder, int * startInorder, int * endInorder) {
int rootValue = startPreorder[0];
BinaryTreeNode * rootNode = new BinaryTreeNode();
rootNode->m_nValue = rootValue;
rootNode->leftChild = NULL;
rootNode->rightChild = NULL;
if (startPreorder == endPreorder) {
if (startInorder == endInorder && *startInorder == *startPreorder) {
return rootNode;
} else {
throw std::invalid_argument("invalid input");
}
}
int *rootInorder = startInorder;
while (rootInorder < endInorder && *rootInorder != rootValue ) {
rootInorder++;
}
if (rootInorder == endInorder && *rootInorder != rootValue) {
throw std::invalid_argument("invalid input");
}
long leftLength = rootInorder - startInorder;
int * leftPreOrderEnd = startPreorder + leftLength;
if (leftLength > 0) {
rootNode->leftChild = constructorCore(startPreorder + 1, leftPreOrderEnd, startInorder, rootInorder - 1);
}
if (endInorder - startInorder > leftLength ) {
rootNode->rightChild = constructorCore( leftPreOrderEnd + 1, endPreorder, rootInorder + 1, endInorder);
}
return rootNode;
}
//只是测试用例,用来输出重建后的结果
struct TestNode {
int leafHeight;
BinaryTreeNode * node;
};
//测试用例可以不看
void traverse (BinaryTreeNode * list) {
if (list == NULL) {
return;
}
TestNode * rootNode = new TestNode();
rootNode->leafHeight = 0;
rootNode->node = list;
int currentLeafHeight = 0;
std::queue<TestNode *> nodeQueue ;
nodeQueue.push(rootNode);
while (!nodeQueue.empty()) {
if (nodeQueue.front()->leafHeight > currentLeafHeight) {
printf("\n");
currentLeafHeight = nodeQueue.front()->leafHeight;
}
printf("%d ",nodeQueue.front()->node->m_nValue);
if (nodeQueue.front()->node->leftChild != NULL) {
TestNode * tNode = new TestNode();
tNode->leafHeight = nodeQueue.front()->leafHeight + 1;
tNode->node = nodeQueue.front()->node->leftChild;
nodeQueue.push(tNode);
}
if (nodeQueue.front()->node->rightChild != NULL) {
TestNode * tNode = new TestNode();
tNode->leafHeight = nodeQueue.front()->leafHeight + 1;
tNode->node = nodeQueue.front()->node->rightChild;
nodeQueue.push(tNode);
}
TestNode * needDelete = nodeQueue.front();
nodeQueue.pop();
delete needDelete->node;
delete needDelete;
}
}
int main() {
int preorder[] = {1,2,4,7,3,5,6,8};
int inOrder[] = {4,7,2,1,5,3,8,6};
BinaryTreeNode * list = constructor(preorder, inOrder, 8);
traverse(list);
}