1138. Postorder Traversal (25)

本文介绍了一种根据先序遍历和中序遍历构造二叉树的方法,并通过递归实现。构造好的二叉树随后进行了后序遍历以验证正确性。该过程涉及读取输入节点序列,构建树结构并输出后序遍历结果。

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

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int n;
vector<int> pre, in, post;
struct node{
  int data; 
  node *l, *r;
};
node *build(int preL, int preR, int inL, int inR){
  if(preL > preR) return NULL;
  node *root = new node;
  root->data = pre[preL];
  int k;
  for(k = inL; k <= inR; k++)
    if(in[k] == pre[preL]) break;
  int leftnum = k - inL;
  root->l = build(preL + 1, preL + leftnum, inL, k - 1);
  root->r = build(preL + leftnum + 1, preR, k + 1, inR);
  return root;
}
void postorder(node *root){
  if(root == NULL) return;
  postorder(root->l);
  postorder(root->r);
  post.push_back(root->data);
}


int main()
{
  cin >> n;
  pre.resize(n);
  in.resize(n);
  for(int i = 0; i < n; i++) cin >> pre[i];
  for(int i = 0; i < n; i++) cin >> in[i];
  node *root = build(0, n-1, 0, n-1);
  postorder(root);
  cout << post[0] << endl;
  return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值