以最简单基本地实现了根据二叉树先序遍历中序遍历建树最后以后序遍历的方式输出。供理解。有不当的地方也在持续更改中
#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;
}