题目
答案
#include<iostream>
#include<malloc.h>
using namespace std;
typedef struct tree* Tree;
struct tree{
int data;
Tree left,right;
};
int after[40],mid[40];
Tree build_tree(int root,int start,int end)
{
if(start>end) return NULL;
int i;
for(i=start;i<=end;i++)
if(mid[i]==after[root]) break;
Tree tmp;
tmp=(Tree)malloc(sizeof(struct tree));
tmp->data=after[root];
tmp->left=build_tree(root-1-(end-i),start,i-1);
tmp->right=build_tree(root-1,i+1,end);
return tmp;
}
void print_tree(Tree tmp)
{
if(tmp)
{
cout<<" "<<tmp->data;
print_tree(tmp->left);
print_tree(tmp->right);
}
}
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++)
cin>>after[i];
for(int i=0;i<n;i++)
cin>>mid[i];
cout<<"Preorder:";
print_tree(build_tree(n-1,0,n-1));
}
注意
- 在函数中创建的tmp结构体变量要记得动态分配内存(即malloc)
- buildTree函数最后记得返回tmp
特别强调
函数中的i千万不要设置为全局变量,因为在递归调用时会出错。
先看代码:
tmp->left=buildTree(root-1-(end-i),start,i-1);
tmp->right=buildTree(root-1,i+1,end);
在这段代码中,如果将i设置为全局变量,i的值会在第一句调用后改变,第二行传进去的i+1值就是错的了
(我看着原来的代码看了看了快一个小时,愣是没看出问题,最后还是用控制变量法才找到问题所在,千万别学我哈)
总结
我看了网上的版本,有的是纯数组,有的是一堆指针看得我头晕,我就做了一定的中和,得出这个使用结构体的一般版本