HDU1710---树(知前序遍历与中序遍历 求后序遍历)

 

 知前序遍历与中序遍历 求后序遍历

#include<iostream>
#include<cstring>
#include<queue>
#include<cstdio>
using namespace std;
bool fist;
const int maxn=1005;
struct tree_node
{
  int value;
  tree_node* leftchild;
  tree_node* rightchild;
  tree_node()
  {
    leftchild=NULL;
    rightchild=NULL;
  }
};
/**
    根据中序遍历,前序遍历建树
    递归 忽略细节  深入至所有结点建立
*/
tree_node* build_tree(int pre[],int in[],int length)
{
  if(length==0)return NULL;///终止条件
  tree_node* temp = new tree_node;
  int pos;
  for(pos=0;pos<length;pos++)///找到根节点->然后根据中序遍历把左子树和右子树分开
  {
    if(in[pos]==pre[0])break;
  }
  temp->value=pre[0];
  temp->leftchild=build_tree(pre+1,in,pos);
  temp->rightchild=build_tree(pre+pos+1,in+pos+1,length-pos-1);
  return temp;
}

void postOrder(tree_node* root)
{
    if(root!=NULL)
    {
        postOrder(root->leftchild);
        postOrder(root->rightchild);
        if(!fist)///根节点输出
        {
          cout<<root->value;
          fist=true;
        }
        else
            cout<<" "<<root->value;
    }
}
int main()
{
  int n;
  int pre[maxn],in[maxn];
  while(scanf("%d",&n)==1)
  {
    fist=false;
    ///input
    for(int i=0;i<n;i++)scanf("%d",&pre[i]);
    for(int i=0;i<n;i++)scanf("%d",&in[i]);
    ///solve
    tree_node* tree=build_tree(pre,in,n);
    postOrder(tree);
    cout<<endl;
  }
  return 0;
}

 

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

const int maxn = 1000 + 5;
int pre[maxn], in[maxn], n, pos[maxn];

void creat(int l, int r, int L, int R) {

    if (L == R) {
        printf("%d ", in[L]);
        return;
    }

    int id = pos[pre[l]];///in中父节点位置
    if(id > L)  creat(l + 1, l + id - L, L, id - 1);//边界, 左
    if(id < R)  creat(l + 1 + id - L, r, id + 1, R);//

    printf("%d%s", in[id], l == 1 ? "\n" : " ");
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
#endif

    while (~scanf("%d", &n)) {
        for (int i = 1; i <= n; ++i) scanf("%d", &pre[i]);
        for (int i = 1; i <= n; ++i) {
            scanf("%d", &in[i]);
            pos[in[i]] = i;
        }
        creat(1, n, 1, n);
    }

    return 0;
}

 

转载于:https://www.cnblogs.com/kimsimple/p/6905032.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值