noj.18 建立二叉树的二叉链表 #数据结构

在这里插入图片描述
思路:

先序根——左——右
中序左——根——右
后序左——右——根

1.在先序中找到根节点
2.在中序中找到根节点
3.求左子树的长度
4.求右子树的长度
5.建立左子树
6.建立右子树
7.输出后序

AC代码:

#include <iostream>
#include<cstring>
using namespace std;
//建立二叉树
struct btnode
{
    char data;
    struct btnode *lchild,*rchild;
};
//s[]先序,r[]中序
char s[201],r[201];
int length;
struct btnode *createbitree(int str1,int str2,int length)
{
  int root;
  int i;
  int llen,rlen;
  struct btnode *p;
  if(length==0) return NULL;
  //1.在先序中找到根节点
  root=s[str1];
  //2.在中序中找到根节点
  i=str2;
  while(r[i]!=root) i++;
  //3.左子树的长度
  llen=i-str2;
  //4.右子树的长度
  rlen=length-llen-1;
  //5.建立左子树
  p=new struct btnode;
  p->data=root;
  p->lchild=createbitree(str1+1,str2,llen);
  //6.建立右子树
  p->rchild=createbitree(str1+1+llen,str2+1+llen,rlen);
  return (p);
}
//输出后序
void postorder(struct btnode *t)
{
    if(t)
	{
		postorder(t->lchild);
		postorder(t->rchild);
		cout << t->data;
	}
}
int main()
{
    struct btnode *t;
	cin >> s >> r;
	length = strlen(s);
	t = createbitree(0, 0, length);
	postorder(t);
    return 0;
}

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

T1009∞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值