pat 1127. ZigZagging on a Tree

本文提供了一道PAT-A级算法题目“ZigZagging on a Tree”的解答方案,该题要求根据给定的中序和后序遍历序列构建二叉树,并按之字形顺序输出节点值。

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

原题链接:https://www.patest.cn/contests/pat-a-practise/1127



1127. ZigZagging on a Tree (30)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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.

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




#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>
#include <vector>
#include <set>
#include <string>
#include <queue>
#include <stack>

using namespace std;

struct node
{
    int num;
    node *lc,*rc;
    int step;
    node() {}
    node(int num, node *lc, node *rc,int step):num(num), lc(lc), rc(rc), step(step) {}
};

int a[35],b[35];
vector<int> vt[35];
int n;

void build(int pos,int l,int r,node *&rt)
{
    int i,tmp=-1;
    for(i=l; i<=r; i++)//注意每次在l~r区间内搜,而不是在1~n区间内搜
    {
        if(a[i]==b[pos])
        {
            tmp=i;
            break;
        }
    }
    if(tmp==-1)//必须保证pos没有超过l~r的范围,,如果没有搜到,就是超过了(也可以直接判断if(l>r))
        return ;
    //rt=(struct node *)malloc(sizeof(struct node));
    //rt->num=b[pos];
    //rt->lc=NULL;
    //rt->rc=NULL;
    rt=new node(b[pos],NULL,NULL,0);
    if(tmp>l)
        build(pos-(r-tmp)-1,l,tmp-1,rt->lc);//注意每次的pos是后序遍历(前序遍历)的根节点位置,,是辅助中序序列找根节点位置的(找左右子树根节点位置时,都要在l~r区间的基础上找)
    if(tmp<r)
        build(pos-1,tmp+1,r,rt->rc);
}

void bfs(node *rt)//因为每一层的输出顺序都不一样,所以每一层都要单独存,然后单独输出,用vector
{
    int i,j;
    int mmax=-1;
    node *s;
    queue<node*> q;
    rt->step=0;
    q.push(rt);
    while(!q.empty())
    {
        s=q.front();
        q.pop();
        vt[s->step].push_back(s->num);
        mmax=max(mmax,s->step);
        if(s->lc!=NULL)
        {
            s->lc->step=s->step+1;
            q.push(s->lc);
        }
        if(s->rc!=NULL)
        {
            s->rc->step=s->step+1;
            q.push(s->rc);
        }
    }
    printf("%d",vt[0][0]);
    for(i=1; i<=mmax; i++)
    {
        if(i&1)
        {
            for(j=0; j<(int)vt[i].size(); j++)
                printf(" %d",vt[i][j]);
        }
        else
        {
            for(j=vt[i].size()-1; j>=0; j--)
                printf(" %d",vt[i][j]);
        }
    }
    printf("\n");
    return ;
}

int main()
{
    int i;
    node *T;
    scanf("%d",&n);
    for(i=1; i<=n; i++)
        scanf("%d",&a[i]);
    for(i=1; i<=n; i++)
        scanf("%d",&b[i]);
    build(n,1,n,T);
    bfs(T);
    return 0;
}




<think>好的,用户想了解二叉树的Z字形遍历算法实现。首先,我需要回忆一下什么是Z字形遍历。记得这是层序遍历的变种,每层交替改变方向,比如第一层从左到右,第二层从右到左,依此类推。根据用户提供的引用,特别是引用[2]中提到的问题解析,Z字遍历的实质是按层访问,一行正向一行反向。 接下来,我需要考虑如何实现这个算法。通常层序遍历使用队列,但这里需要每层改变方向,可能需要记录当前层数或者使用双端队列来调整添加节点的顺序。引用[4]提到在BFS中,左到右遍历时用FIFO,添加到队尾;右到左时用FILO,添加到队头。这提示可以使用双端队列,或者普通队列配合标记方向,并在处理每层时根据方向决定如何处理节点。 然后,我需要考虑具体步骤。初始化队列,加入根节点。然后循环处理每一层,记录当前层的大小。根据当前层的方向,决定是正序还是逆序保存结果。同时,在遍历下一层节点时,可能需要调整子节点的添加顺序,比如在右到左时,先右子节点再左子节点,但这样可能会影响下一层的处理顺序。或者,保持正常的子节点添加顺序,但在保存结果时反转当前层的列表。 根据引用[4]的实现方法,他们可能在右到左时,将子节点插入队列头部,这样下一层处理时会先访问这些节点。不过这样可能会改变队列的FIFO特性,需要仔细处理。另一种方法是正常处理队列,但在收集完当前层的节点值后,根据层数的奇偶性决定是否反转该层的列表。 例如,使用一个布尔变量标记是否需要反转,初始为False(第一层不需要反转)。处理完每一层后,切换这个布尔值。然后在收集节点值时,如果是偶数层(比如第二层),则反转该层的列表。这种方法实现起来比较简单,不需要改变队列的结构,只需在保存结果时处理。 然后,代码实现方面,可以用队列进行BFS,维护一个结果列表。每次处理一层节点,将它们的值存入临时列表,根据当前层的方向决定是否反转,然后将该临时列表加入结果。同时,将子节点按正常顺序加入队列,这样下一层的处理顺序不会被打乱,只是保存时反转即可。 这样实现的好处是代码逻辑清晰,容易理解,且不需要复杂的队列操作。例如,在Python中,可以用deque来实现队列,每层处理时记录当前层的节点数,循环取出节点,收集子节点,然后根据层数的奇偶性决定是否反转当前层的值列表。 现在,需要考虑是否需要处理空树的情况,即根节点为空时直接返回空列表。同时,循环中逐层处理,直到队列为空。 最后,编写示例代码,并确保符合用户提到的格式要求,如行内公式用$...$,独立公式用$$...$$。可能还需要解释时间复杂度,比如O(n),空间复杂度O(n)等。 总结,Z字形遍历的关键点在于层序遍历的基础上,每隔一层反转结果。实现时可以使用BFS,配合方向标记,决定是否反转当前层的节点值列表。</think>二叉树的Z字形层序遍历(Zigzag Level Order Traversal)是一种在每层交替改变遍历方向的算法。其核心思想基于广度优先搜索(BFS),通过队列和方向控制实现[^2][^4]。 ### 算法实现步骤 1. **初始化队列**:将根节点加入队列,并设置方向标志`left_to_right`为`True`(表示第一层从左到右) 2. **逐层遍历**: - 记录当前层的节点数量`level_size` - 用临时列表存储当前层节点的值 3. **处理节点**: - 根据方向标志决定节点值的存储顺序 - 将子节点按正常顺序(左→右)加入队列 4. **方向切换**:每层处理完成后翻转方向标志 5. **时间复杂度**:$O(n)$,其中$n$为节点数 ### Python代码示例 ```python from collections import deque class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def zigzagLevelOrder(root: TreeNode) -> list[list[int]]: if not root: return [] result = [] queue = deque([root]) left_to_right = True # 方向控制标志 while queue: level_size = len(queue) current_level = deque() # 使用双端队列优化插入效率 for _ in range(level_size): node = queue.popleft() # 根据方向选择插入位置 if left_to_right: current_level.append(node.val) else: current_level.appendleft(node.val) # 按正常顺序添加子节点 if node.left: queue.append(node.left) if node.right: queue.append(node.right) result.append(list(current_level)) left_to_right = not left_to_right # 切换方向 return result ``` ### 关键点说明 1. **双端队列优化**:使用`deque`的左右插入操作使时间复杂度保持在$O(n)$ 2. **子节点处理顺序**:始终保持子节点按左→右顺序入队,仅改变当前层值的存储顺序 3. **方向控制逻辑**:通过布尔值`left_to_right`实现交替方向控制 $$ \text{空间复杂度} = O(n) \quad \text{(队列最大存储量)} $$
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值