PAT 1020. Tree Traversals

5 篇文章 0 订阅

题目链接

通过后序和中序的序列来构建这棵树,然后输出层序序列。
思路都是一样的。递归的思想。后序的最后一个点就是根节点,然后就在中序中去寻找该节点。则左边为左子树中序,右边为右子树中序。
一开始用数组去实现的递归,不知为何总是崩溃。于是照着别人的代码敲了一遍。其中的bfs还是要掌握的。

还有就是递归的时候要给节点赋予实体。
Tree *tree= (Tree *)malloc(sizeof(Tree));写成Tree *tree;是不对的。程序会崩溃,跑不了。因为你不给他分配有空间的实体的话,这个树是不存在的,其中的tree也只是一个形参,即便你赋值了程序结束后就不存在,只有用malloc把他变成实参。

#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<stdlib.h>
#include<iostream>
#include<string.h>
#include<queue>
using namespace std;

typedef struct Tree{
        int data;
        Tree *left;
        Tree *right;
        }Tree;

int pos[33],in[33];

Tree *buildtree(int pl,int pr,int il,int ir)
{
        if(pl>pr)
                return NULL;

        int p=il;
        while(in[p]!=pos[pr])
                p++;

        Tree *tree= (Tree *)malloc(sizeof(Tree));
        tree->data=in[p];
        tree->left=buildtree(pl,pr-ir+p-1,il,p-1);
        tree->right=buildtree(pr-ir+p,pr-1,p+1,ir);
        return tree;
}

void printLevelOrder(Tree *root)
{
        Tree *tr;
        tr=NULL;
        bool flag=false;
        queue<Tree *> que;
        que.push(root);
        while(!que.empty())
        {
                tr=(Tree *)que.front();
                que.pop();
                if(tr==NULL)
                        continue;
                if(!flag)
                {
                        printf("%d",tr->data);
                        flag=true;
                }
                else
                {
                        printf(" %d",tr->data);
                }
                que.push(tr->left);
                que.push(tr->right);
        }
}


int main()
{
        int n,i;
        scanf("%d",&n);
        for(i=0;i<n;i++)
                scanf("%d",&pos[i]);
        for(i=0;i<n;i++)
                scanf("%d",&in[i]);

        Tree* lol=buildtree(0,n-1,0,n-1);
        printLevelOrder(lol);
        return 0;


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值