中序和后序恢复二叉树问题
写了个恢复代码,思路觉得没有错,语法也没有错,执行的时候却出错了,调试了半天还是调不出来,请各位大虾帮帮忙,看下。
以前是我的代码:
#include<iostream>
using namespace std;
const int N=30;
struct node
{
char data;
struct node *lt,*rt;
};
void mid_post_creat(char *mid,char *post,int len,struct node **root)//len代表数组长度
{
char *m;
int k;
if(len<=0)
{
*root=NULL;
}
for(m=mid;m<mid+len;m++)
{
if(*m==*(post+len-1))
{
k=m-mid;
*root=new node;
(*root)->data=*(post+len-1);
break;
}
}
mid_post_creat(mid,post,k,&((*root)->lt));
mid_post_creat(mid+k+1,post+k,len-k-1,&((*root)->rt));
cout<<"恢复成功"<<endl;
}
int main()
{
struct node *root;
int len;
char mid[N]={NULL},post[N]={NULL};
cout<<"请输入中序序列"<<endl;
cin>>mid;
cout<<"请输入后序序列"<<endl;
cin>>post;
cout<<"请输入结点数"<<endl;
cin>>len;
void mid_post_creat(char *mid,char *post,int len,struct node **root);
mid_post_creat(mid,post,len,&root);
return 0;
}
[解决办法]
- C/C++ code
#include<iostream>#include<cstdio>#include<cstring>using namespace std;struct BinaryTreeNode{ char c; BinaryTreeNode *lchild, *rchild; BinaryTreeNode() { lchild = NULL, rchild = NULL; }};struct BinaryTreeNode *root;char preorder[100], inorder[100], postorder[100];void preSearch(BinaryTreeNode *root) //先序遍历树{ if(root != NULL) { printf("%c", root->c); preSearch(root->lchild); preSearch(root->rchild); } return ;}void midSearch(BinaryTreeNode *root) //中序遍历树{ if(root != NULL) { midSearch(root->lchild); printf("%c", root->c); midSearch(root->rchild); } return ;}void postSearch(BinaryTreeNode *root) //后序遍历树{ if(root != NULL) { postSearch(root->lchild); postSearch(root->rchild); printf("%c", root->c); } return ;}void BuildTreeFromPostAndMid(BinaryTreeNode * &root, int ll, int lr, int len, int &now)//根据中序和后序求树{ root = new BinaryTreeNode(); root->c = *(postorder + now); int pos = (int)(strchr(inorder, *(postorder + now)) - inorder); now--; if(now < 0) return ; if(pos + 1 <= lr) { BinaryTreeNode *t = new BinaryTreeNode(); root->rchild = t; BuildTreeFromPostAndMid(root->rchild, pos + 1, lr, len, now); } if(pos - 1 >= ll) { BinaryTreeNode *t = new BinaryTreeNode(); root->lchild = t; BuildTreeFromPostAndMid(root->lchild, ll, pos - 1, len, now); }}//释放二叉树inline void DeleteBinaryTree(BinaryTreeNode * &root){ if(root) { DeleteBinaryTree(root->lchild); //释放左子树 DeleteBinaryTree(root->rchild); //释放右子树 delete root; //释放根结点 }}int main(void){ gets(inorder); //中序序列 gets(postorder); //后序序列 int now = strlen(postorder)-1; BuildTreeFromPostAndMid(root, 0, strlen(postorder) - 1, strlen(postorder), now); preSearch(root); DeleteBinaryTree(root); puts(""); return 0;}