L6Alpa


私信TA

用户名:dotcpp0688309

访问量:320

签 名:

等  级
排  名 2001
经  验 2414
参赛次数 0
文章发表 6
年  龄 0
在职情况 学生
学  校 gz
专  业

  自我简介:

TA的其他文章

来个C++的题解
浏览:26

解题思路:
以先序遍历为基础,找到root后在中序遍历中找root的位置并设置好范围len,变换pre和in数组的head指针

参考代码:

#include<bits/stdc++.h>

#define rep(i,a,b) for(int i=a;i<=b;i++)

using namespace std;

int read(){

int x=0,f=1;

char ch=getchar();

while(ch<'0'||ch>'9') {

if(ch=='-')

f=-1;

ch=getchar();

}

while(ch>='0' && ch<='9')

x=x*10+ch-'0',ch=getchar();

return x*f;

}

struct Node{

char data;

Node *lchild,*rchild;

};

void postOrder(Node *root)

{

if(root==NULL)

return;

postOrder(root->lchild);

postOrder(root->rchild);

cout<<root->data;

}

int find(char c,char *in,int len)

{

for(int i=0;i<len;i++)

if(in[i]==c)

return i;

return -1;

}

Node *msn(char *pre,char *in,int len)

{

if(len<=0)

return NULL;

Node *root=new Node;

int index=find(*pre,in,len);

root->data=*pre;

root->lchild=msn(pre+1,in,index);

root->rchild=msn(pre+index+1,in+index+1,len-index-1);

return root;

}

const int N=1000;

int main()

{

char *pre=new char[N],*in=new char[N];

cin>>pre;

cin>>in;

Node *root;

root=msn(pre,in,strlen(pre));

postOrder(root);

return 0;

}


 

0.0分

1 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区