·注意:前序序列和中序序列中都不能有重复的数字。
#include "stdafx.h"
#include <iostream>
using namespace std;
struct BinaryTreeNode {
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
BinaryTreeNode* ConstructCore( int *const startPreorder, int *const endPreorder, int *const startInorder, int *const endInorder) {
int rootValue = startPreorder[0];
BinaryTreeNode *root = new BinaryTreeNode();
root->m_nValue = rootValue;
root->m_pLeft = root->m_pRight = NULL;
if (startPreorder == endPreorder) {
if (startInorder == endInorder && *startPreorder == *startInorder) { //保证两个序列没有任何问题
return root;
}
else {
throw std::exception("Invalid input");
}
}
int *rootInorder = startInorder;
while (rootInorder < endInorder && *rootInorder != rootValue) { // 这个条件应该有问题,书上应该错了。P64
rootInorder++;
}
if (rootInorder == endInorder && *rootInorder != rootValue) {
cout << "zxc" << endl;
throw std::exception("Invalid input");
}
int leftLength = rootInorder - startInorder; //不算root节点
int *leftPreorderEnd = startPreorder + leftLength;
if (leftLength > 0){
root->m_pLeft = ConstructCore(startPreorder+1, leftPreorderEnd, startInorder, rootInorder-1);
}
if (leftLength < endPreorder - startPreorder) {
root->m_pRight = ConstructCore(leftPreorderEnd + 1, endPreorder, rootInorder+1, endInorder);
}
return root;
}
BinaryTreeNode* Construct(int* preorder, int *inorder, int length) {
if (preorder == NULL || inorder == NULL || length <= 0) {
return NULL;
}
return ConstructCore(preorder, preorder + length - 1, inorder, inorder + length - 1);
}
/*********************************
* 可视化树结构
**********************************/
void padding(char ch, int n)
{
int i;
for (i = 0; i < n; i++)
putchar(ch);
}
void print_node(struct BinaryTreeNode *root, int level)
{
if (root == NULL)
{
padding('\t', level);
puts("NIL");
}
else
{
print_node(root->m_pRight, level + 1);
padding('\t', level);
printf("%d\n", root->m_nValue);
print_node(root->m_pLeft, level + 1);
}
}
void print_tree(struct BinaryTreeNode* root)
{
print_node(root, 0);
printf("-------------------------------------------\n");
}
int main() {
int preorder[3] = {1,2,3};
int inorder[3] = {4,5,6};
BinaryTreeNode *root = NULL;
root = Construct(preorder, inorder, 3);
print_tree(root);
return 0;
}