题目:输入某二叉树前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不包含重复的数字。例如输入前序遍历序列{1, 2, 4, 7, 3, 5, 6, 8}和中序遍历序列{4, 7, 2, 1, 5, 3, 8, 6},则重建出该二叉树。
struct BinaryTreeNode {
int m_nValue;
BinaryTreeNode *m_pleft;
BinaryTreeNode *m_pright;
};
思路:前序遍历的第一个结点为根节点,然后根据该结点的值在中序遍历的数组中找出该值,则该值的左侧为二叉树的左子树,右侧为二叉树的右子树,然后,递归重建二叉树。
#include <iostream>
#include <stdio.h>
using namespace std;
struct BinaryTreeNode {
int m_nValue;
BinaryTreeNode *m_pleft;
BinaryTreeNode *m_pright;
};
BinaryTreeNode* build(int*a,int la,int ra,int* b,int lb,int rb) {
if(la > ra)
return NULL;
//用于统计左子树结点个数
int len = 0;
// 在中序遍历中找到根结点的值
for(int i=lb;i<=rb;i++) {
if(a[la] == b[i]) {
break;
}
len++;
}
//创建结点 前序遍历序列的第一个数字是根结点的值
BinaryTreeNode *root = new BinaryTreeNode();
root->m_nValue = a[la];//即 b[lb+len]
//构造左子树,左子树结点个数个数为len
root->m_pleft = build(a,la+1,la+len,b,lb,lb+len-1);
//构造右子树, 右子树结点个数为rb-lb-len
root->m_pright = build(a,ra-rb+lb+len+1,ra,b,lb+len+1,rb);
return root;
}
BinaryTreeNode* BuildBinaryTree(int* a,int* b,int length) {
if(a == NULL || b == NULL || length <= 0)
return NULL;
return build(a,0,length-1,b,0,length-1);
}
void Traverse(BinaryTreeNode* p) {
if(p != NULL) {
cout<<p->m_nValue<<" ";
Traverse(p->m_pleft);
Traverse(p->m_pright);
}
}
// ====================测试代码====================
void Test(char* testName, int* preorder, int* inorder, int length)
{
if(testName != NULL)
printf("%s begins:\n", testName);
printf("The preorder sequence is: ");
for(int i = 0; i < length; ++ i)
printf("%d ", preorder[i]);
printf("\n");
printf("The inorder sequence is: ");
for(int i = 0; i < length; ++ i)
printf("%d ", inorder[i]);
printf("\n");
BinaryTreeNode* root = BuildBinaryTree(preorder, inorder, length);
Traverse(root);
cout<<endl;
}
// 普通二叉树
// 1
// / \
// 2 3
// / / \
// 4 5 6
// \ /
// 7 8
void Test1()
{
const int length = 8;
int preorder[length] = {1, 2, 4, 7, 3, 5, 6, 8};
int inorder[length] = {4, 7, 2, 1, 5, 3, 8, 6};
Test("Test1", preorder, inorder, length);
}
// 所有结点都没有右子结点
// 1
// /
// 2
// /
// 3
// /
// 4
// /
// 5
void Test2()
{
const int length = 5;
int preorder[length] = {1, 2, 3, 4, 5};
int inorder[length] = {5, 4, 3, 2, 1};
Test("Test2", preorder, inorder, length);
}
// 所有结点都没有左子结点
// 1
// \
// 2
// \
// 3
// \
// 4
// \
// 5
void Test3()
{
const int length = 5;
int preorder[length] = {1, 2, 3, 4, 5};
int inorder[length] = {1, 2, 3, 4, 5};
Test("Test3", preorder, inorder, length);
}
// 树中只有一个结点
void Test4()
{
const int length = 1;
int preorder[length] = {1};
int inorder[length] = {1};
Test("Test4", preorder, inorder, length);
}
// 完全二叉树
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
void Test5()
{
const int length = 7;
int preorder[length] = {1, 2, 4, 5, 3, 6, 7};
int inorder[length] = {4, 2, 5, 1, 6, 3, 7};
Test("Test5", preorder, inorder, length);
}
// 输入空指针
void Test6()
{
Test("Test6", NULL, NULL, 0);
}
int main(int argc, char *argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
return 0;
}