【重建二叉树】牛客 二叉树遍历(前中->后)、甲1020(后中->层)、甲1086(前中->后)、甲1127(中后->前、变形层序)

题目描述

二叉树的前序、中序、后序遍历的定义: 前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树; 中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树; 后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。 给定一棵二叉树的前序遍历和中序遍历,求其后序遍历(提示:给定前序遍历与中序遍历能够唯一确定后序遍历)。

输入描述:

两个字符串,其长度n均小于等于26。
第一行为前序遍历,第二行为中序遍历。
二叉树中的结点名称以大写字母表示:A,B,C....最多26个结点。

输出描述:

输入样例可能有多组,对于每组测试样例,
输出一行,为后序遍历的字符串。

示例1

输入

复制

ABC
BAC
FDXEAG
XDEFAG

输出

复制

BCA
XEDGAF

#include <stdio.h>
#include <cstdio>
#include <string>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
#include <stack>
#include <map>
#include <set>
using namespace std;
char pre[100],in[100];
typedef struct node
{
    char data;
    node *lchild,*rchild;
}node;
node* Create(int preL,int preR,int InL,int InR)  //前序/中序
{
    if(preL>preR)
    {
        return NULL;
    }
    //printf("%d",preL);
    //printf("%c",pre[preL]);
    node *root=new node;
    root->data=pre[preL];
    int k;
    for(int i=InL;i<=InR;i++)
    {
        if(in[i]==pre[preL])
        {
            k=i;
            break;
        }
    }
    //printf("%d",k);
    int numLeft=k-InL;//左子树节点个数,(没有减一,因为k为根结点的位置,不算),则前序遍历中左节点下标为从PreL+1到PreL+numLeft!
    root->lchild=Create(preL+1,preL+numLeft,InL,k-1);  //下标很重要!!!
    root->rchild=Create(preL+numLeft+1,preR,k+1,InR);
    return root;
}
void PostTraval(node *root)
{
    if(root==NULL)
        return;
    if(root)
    {
        PostTraval(root->lchild);
        PostTraval(root->rchild);
        printf("%c",root->data);
    }
}
int main(){
    scanf("%s %s",pre,in);
    int len1=strlen(pre);
    int len2=strlen(in);
    node *root=Create(0,len1-1,0,len2-1);
    PostTraval(root);
}

 

1020 Tree Traversals (25 分)

Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

Sample Output:

4 1 6 3 5 7 2

 

#include <stdio.h>
#include <cstdio>
#include <string>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
#include <stack>
#include <map>
#include <set>
using namespace std;
int n,post[10001],In[10001];
typedef struct node
{
    int data;
    node *lchild,*rchild;
}node;
node *Create(int PostL,int PostR,int inL,int inR)
{
    if(PostL>PostR)
    {
        return NULL;
    }
    node *root=new node;
    root->data=post[PostR];
    int k;
    for(int i=inL;i<=inR;i++)
    {
        if(In[i]==root->data)
        {
            k=i;
            break;
        }
    }
    int numLeft=k-inL;//左子树的节点个数,则后序下标是从PostL到PostL+numLeft-1!!!!
    root->lchild=Create(PostL, PostL+numLeft-1,inL,k-1); //难点:下标,不要搞错了
    root->rchild=Create(PostL+numLeft,PostR-1,k+1,inR);
    return root;
}
void LevelTraval(node *root)
{
    queue<node*>q;
    q.push(root);
    int flag=0;
    while(!q.empty())
    {
        node *tmp=q.front();
        if(flag==0)
        {
            printf("%d",tmp->data);
            flag=1;
        }
        else{
            printf(" %d",tmp->data);
        }
        q.pop();
        if(tmp->lchild) q.push(tmp->lchild);
        if(tmp->rchild) q.push(tmp->rchild);
    }
}
int main(){
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        scanf("%d",&post[i]);
    }
    for (int i=0;i<n;i++) {
        scanf("%d",&In[i]);
    }
    node *root=Create(0,n-1,0,n-1);
    LevelTraval(root);
}

 

1086 Tree Traversals Again (25 分)

An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the stack operations are: push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5); push(6); pop(); pop(). Then a unique binary tree (shown in Figure 1) can be generated from this sequence of operations. Your task is to give the postorder traversal sequence of this tree.


Figure 1

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (≤30) which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to N). Then 2N lines follow, each describes a stack operation in the format: "Push X" where X is the index of the node being pushed onto the stack; or "Pop" meaning to pop one node from the stack.

Output Specification:

For each test case, print the postorder traversal sequence of the corresponding tree in one line. A solution is guaranteed to exist. All the numbers must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:

6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop

Sample Output:

3 4 2 6 5 1

Push的数字顺序就是整棵树的先根遍历序列,Pop的数字顺序就是整棵树的中根遍历序列,于是问题就变成了如何根据一棵树的先根遍历序列和中根遍历序列得出树的后根遍历序列。

#include <stdio.h>
#include <cstdio>
#include <string>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
#include <stack>
#include <map>
#include <set>
using namespace std;
int pre[10001],in[10001],post[10001];
int n;
int s1=0;
typedef struct node
{
    int data;
    node *lchild,*rchild;
}node;
node* Create(int preL,int preR,int inL,int inR)
{
    if(preL>preR)
    {
        return NULL;
    }
    node *root=new node;
    root->data=pre[preL];
    int k;
    for(int i=inL;i<=inR;i++)
    {
        if(in[i]==root->data)
        {
            k=i;
            break;
        }
    }
    int numLeft=k-inL;
    root->lchild=Create(preL+1,preL+numLeft,inL,k-1);
    root->rchild=Create(preL+numLeft+1,preR, k+1, inR);
    return root;
}
void PostTraval(node *root)
{
    if(root)
    {
        PostTraval(root->lchild);
        PostTraval(root->rchild);
        //printf("%d",root->data);
        post[s1++]=root->data;
    }
}
int main(){
    scanf("%d",&n);
    stack<int>s;
    int k1=0,k2=0;
    for(int i=0;i<2*n;i++)
    {
        char str[1001];
        scanf("%s",str);
        if(strcmp(str,"Push")==0)
        {
            int x;
            scanf("%d",&x);
            pre[k1++]=x;
            s.push(x);
        }
        else if(strcmp(str,"Pop")==0)
        {
            in[k2++]=s.top();
            s.pop();
        }
    }
    //    for(int i=0;i<k1;i++)
    //        printf("%d ",pre[i]);
    //    for(int i=0;i<k2;i++)
    //        printf("%d ",in[i]);
    node *root=Create(0,k1-1,0,k2-1);
    PostTraval(root);
    for(int i=0;i<s1;i++)
    {
        if(i==0)
        printf("%d",post[i]);
        else
         printf(" %d",post[i]);
    }
}

 

 

1127 ZigZagging on a Tree (30 分)

Suppose that all the keys in a binary tree are distinct positive integers. A unique binary tree can be determined by a given pair of postorder and inorder traversal sequences. And it is a simple standard routine to print the numbers in level-order. However, if you think the problem is too simple, then you are too naive. This time you are supposed to print the numbers in "zigzagging order" -- that is, starting from the root, print the numbers level-by-level, alternating between left to right and right to left. For example, for the following tree you must output: 1 11 5 8 17 12 20 15.

zigzag.jpg

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary tree. The second line gives the inorder sequence and the third line gives the postorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the zigzagging sequence of the tree in a line. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:

8
12 11 20 17 1 15 8 5
12 20 17 11 15 8 5 1

Sample Output:

1 11 5 8 17 12 20 15

题中的序列是按层输出的,第一层从右向左输出,第二层从左向右输出,第三层又从右向左……如此循环往复直至输出整棵树所有节点。为了实现这样的输出序列,可以定义一个vector的数组levelElement,以层数作为数组下标,将每一层的元素都按从左向右的顺序存储在对应的levelElement的一个元素vector中,这一过程深度优先搜索或广度优先搜索均可实现。然后遍历LevelElement,如果当前所处层数为偶数(层数由0开始编号),就从前向后输出levelElement中元素;否则从后向前输出。

#include <stdio.h>
#include <cstdio>
#include <string>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
#include <stack>
#include <map>
#include <set>
using namespace std;
int n;
int inorder[1001];  //中序遍历序列
int postorder[1001];  //后序遍历序列
vector<vector<int>>level(1005);
int maxlevel;
typedef struct node
{
    int data;
    int lev;
    struct node *lchild,*rchild;
}node;
node *Create(int postL,int postR,int inL,int inR)  //后序+中序建树!!!难点!!
{
    if(postL>postR)
        return NULL;
    struct node *root=new node;
    root->data=postorder[postR];
    int k;
    for(int i=inL;i<=inR;i++)
    {
        if(inorder[i]==root->data)
        {
            k=i;
            break;
        }
    }
    int numLeft=k-inL;  //左子树节点个数
    root->lchild=Create(postL,postL+numLeft-1,inL,k-1);
    root->rchild=Create(postL+numLeft,postR-1,k+1,inR);
    return root;
}
void levelTraval(node *root)
{
    queue<node*>s;
    s.push(root);
    root->lev=1;
    while(!s.empty())
    {
        node *t=s.front();
        s.pop();
        level[t->lev].push_back(t->data);  //记录每一层的节点!!!
        maxlevel=max(maxlevel,t->lev);
        if(t->lchild)
        {
            t->lchild->lev=t->lev+1;
            s.push(t->lchild);
        }
        if(t->rchild)
        {
            t->rchild->lev=t->lev+1;
            s.push(t->rchild);
        }
    }
}
int main(){
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        scanf("%d",&inorder[i]);
    }
    for(int i=0;i<n;i++)
    {
        scanf("%d",&postorder[i]);
    }
    node *root;
    root=Create(0,n-1,0,n-1);
    levelTraval(root);
    int flag=0;
    for(int i=1;i<=maxlevel;i++)
    {
        if(i%2==1)
        {
            for(int j=level[i].size()-1;j>=0;j--)
            {
                if(flag==0)
                {
                    flag=1;
                    printf("%d",level[i][j]);
                }
                else
                {
                    printf(" %d",level[i][j]);
                }
            }
        }
        else
        {
            vector<int>::iterator it;
            for(it=level[i].begin();it!=level[i].end();it++)
            {
                printf(" %d",*it);
            }
        }
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值