简单形式写下思想。仅供交流。有问题还望指正。
#include<iostream>
using namespace std;struct BinaryTreeNode
{
int value;
BinaryTreeNode* left;
BinaryTreeNode* right;
};
//int beforeSequence[8] = {1, 2, 4, 7, 3, 5, 6, 8};
//int midSequence[8] = {4, 7, 2, 1, 5, 3, 8, 6};
int beforeSequence[8] = {1, 2, 3, 4, 5, 6, 7, 8};
int midSequence[8] = {8, 4, 2, 5, 1, 6, 3, 7};
int nodeSize = 8;
int findFirstIndex(int starting, int ending) //以中序遍历数字串为依据。每次找到串中第一次在先序遍历中出现的元素。输出其在中序遍历串中的下标
{
int i, j;
for (i = 0; i < nodeSize; i++)
{
for (j = starting; j <= ending; j++)
{
if (beforeSequence[i] == midSequence[j])
return j;
}
}
return -1;
}
BinaryTreeNode* createBinaryTree(int starting, int ending)
{
if (starting > ending)
return NULL;
else
{
BinaryTreeNode* bi = new BinaryTreeNode;
int index = findFirstIndex(starting, ending); //先序遍历第一次出现的作为根节点
if (index == -1)
{
cout<<"error";
return NULL;
}
bi->value = midSequence[index];
bi->left = createBinaryTree(starting, index - 1);
bi->right = createBinaryTree(index + 1, ending);
return bi;
}
}
void printAfter(BinaryTreeNode* t)//结果以后序遍历的形式输出。简单测试正确。思想仅供交流
{
if (t == NULL)
{
return;
}
else
{
printAfter(t->left);
printAfter(t->right);
cout<< t->value;
}
}
int main()
{
BinaryTreeNode* node = createBinaryTree(0, 7);
printAfter(node);
return 0;
}