nyoj221 已知条件构造二叉树

本文介绍了一种根据前序遍历和中序遍历结果重建二叉树的方法,并通过C++代码实现该算法。文章详细展示了如何递归地构建二叉树,并实现了后序遍历以验证构造结果。

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

链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=221

由于二叉树本身是递归的结构,前序遍历的第一个节点一定是根节点,而通过对后序的结果进行查找,后续第一个节点的距离与前序第一个相同的结点的距离即为左子树的节点的个数,同理右子树同理、

#include<iostream>
#include<stdio.h>
#include<cstring>
#define Max 27
using namespace std;
char pstr[Max],instr[Max];
struct Node
{
 char n;
 Node *leftchild,*rightchild;
 Node(char s):n(s),leftchild(NULL),rightchild(NULL) {}
};
void postorder(Node *roo);
Node* Rebulid(char pstr[],char instr[],int len);
int main()
{
 while(scanf("%s%s",&pstr,&instr)!=EOF)
 {
  Node *root=Rebulid(pstr,instr,int(strlen(pstr)));
  postorder(root);
  cout<<endl;
 }
 system("pause");
 return 0;
}
Node* Rebulid(char pstr[],char instr[],int len)
{
 if(len<=0) return NULL;
 Node *newNode=new Node(pstr[0]);
 int k,temp;
 for(k=0;k<len;++k)
 {
  if(instr[k]==pstr[0])
  {
   temp=k;
   break;
  }
 }
 newNode->leftchild=Rebulid(pstr+1,instr,temp);
 newNode->rightchild=Rebulid(pstr+temp+1,instr+temp+1,len-temp-1);
 return newNode;
}
void postorder(Node *roo)
{
 if(roo!=NULL)
 {
  postorder(roo->leftchild);
  postorder(roo->rightchild);
  cout<<roo->n;
 }
 else return;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值