根据先序,中序,求后序遍历#include<cstdio> #include<cstring> #include<iostream> using namespace std; struct Node...

本文介绍了一种根据先序序列和中序序列构造二叉树的方法,并实现了树的后序遍历输出。通过输入两个字符串序列,程序能够创建对应的二叉树结构并输出后序遍历结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;

struct Node
{
char data;
Node *lchild,*rchild;
};

Node* createtree(string pre,string in)
{
Node *root=NULL;
if(pre.length()>0)
{
root=new Node;
root->data=pre[0];
int index=in.find(root->data);
root->lchild=createtree(pre.substr(1,index),in.substr(0,index));
root->rchild=createtree(pre.substr(index+1),in.substr(index+1));
}
return root;
}

void posorder(Node *root)
{
if(root!=NULL)
{
posorder(root->lchild);
posorder(root->rchild);
cout<<root->data;
}
}

int main()
{
string pre_str,in_str;
Node *root;
printf("请输入二叉树的先序序列换行后输入中序序列\n");
while(cin>>pre_str>>in_str)
{
root=createtree(pre_str,in_str);
posorder(root);
cout<<endl;
}
return 0;
}

转载于:https://www.cnblogs.com/-xss/p/6011928.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值