1127 ZigZagging on a Tree (30 分)

本文介绍了一种独特的二叉树遍历方式——锯齿形层次遍历,通过给定的中序和后序遍历序列构建二叉树,并按从根节点开始的锯齿形路径输出节点值。此方法首先根据序列构建树,然后采用广度优先搜索策略,交替地从左到右和从右到左打印每一层的节点。

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

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

 

#include<bits/stdc++.h>
using namespace std;
int in[1005],post[1005];
typedef struct node
{
    int data;
    struct node *lchild,*rchild;
}node,*Tree;
Tree Create(int inl,int inr,int postl,int postr)
{
    if(postl>postr)
        return NULL;
    Tree root = new node;
    root->data = post[postr];
    int k;
    for(k = inl;k<=inr;k++)
    {
        if(in[k]==post[postr])
            break;
    }
    int leftnum = k-inl;
    root->lchild = Create(inl,k-1,postl,postl+leftnum-1);
    root->rchild = Create(k+1,inr,postl+leftnum,postr-1);
    return root;
}

void bfs(Tree root)
{
    queue<Tree>q;
    q.push(root);
    cout<<root->data;
    int level=2;
    while(!q.empty())
    {
        vector<Tree>v;
        while(!q.empty())
        {
            Tree t= q.front();
            q.pop();
            if(t->lchild)
                v.push_back(t->lchild);
            if(t->rchild)
                v.push_back(t->rchild);
        }
        for(int i=0;i<v.size();i++)
            q.push(v[i]);
        if(level%2==0)
        {
            for(int i=0;i<v.size();i++)
                cout<<" "<<v[i]->data;
        }
        else
        {
            for(int i=v.size()-1;i>=0;i--)
                cout<<" "<<v[i]->data;
        }
        level++;
    }
}
int main()
{
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
        scanf("%d",&in[i]);
    for(int i=0;i<n;i++)
        scanf("%d",&post[i]);
    Tree root;
    root = Create(0,n-1,0,n-1);
    bfs(root);
}
 

<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、付费专栏及课程。

余额充值