127. ZigZagging on a Tree (30)

本文介绍了一种特殊的二叉树遍历方式——锯齿形层次遍历,即从根节点开始,逐层交替地从左到右和从右到左打印节点值。文章提供了一个实现该遍历方式的示例代码,并详细解释了如何通过构建二叉树并采用两种不同的层次遍历来完成这一任务。

127. 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.

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

127. ZigZagging on a Tree (30)


/*************************************************************
Author : qmeng
MailTo : qmeng1128@163.com
QQ     : 1163306125
Blog   : http://blog.youkuaiyun.com/Mq_Go/
Create : 2018-03-03 16:02:07
Version: 1.0
**************************************************************/
#include <cstdio>
#include <iostream>
#include <queue>
#include <cstdlib>
#include <vector>
using namespace std;
const int MAX = 30;
struct Tree{
    Tree *le;
    Tree *ri;
    int data;
};
bool key = true;
Tree *Tr;
int in[MAX],pos[MAX];
int n;
queue<Tree *> que,queM;
vector<int> v1,v2;
Tree *buildTree(int il,int ir,int pl,int pr){
    if(pl>pr)return NULL;
    int p = il;
    while(in[p] != pos[pr])p++;

    Tree *root = (Tree *) malloc (sizeof(Tree));
    root->data = in[p];
    root->le = buildTree(il,p-1,pl,pr-ir+p-1);
    root->ri = buildTree(p+1,ir,pr-ir+p,pr-1);
    return root;

}
void printLevelTree1(Tree *root){    
    Tree *Tr = NULL;
    que.push(root);
    while(!que.empty()){
        Tree *Tr = que.front();
        que.pop();
        if(Tr==NULL)continue;
        v1.push_back(Tr->data);
        //printf("%d ",Tr->data);
        que.push(Tr->le);
        que.push(Tr->ri);
    }
}
void printLevelTree2(Tree *root){    
    Tree *Tr = NULL;
    que.push(root);
    while(!que.empty()){
        Tree *Tr = que.front();
        que.pop();
        if(Tr==NULL)continue;
        v2.push_back(Tr->data);
        //printf("%d ",Tr->data);
        que.push(Tr->ri);
        que.push(Tr->le);
    }
}
/*
1 11 5 12 17 8 20 15
1 5 11 8 17 12 15 20
*/
void print(int k){
    if(k>=n)return;
    int p = k;
    if(key == true){
        while(v1[p]!=v2[k]){
            printf(" %d",v1[p]);
            p++;
        }
        printf(" %d",v1[p]);
        key = false;
    }else{
        while(v2[p]!=v1[k]){
            printf(" %d",v2[p]);
            p++;
        }
        printf(" %d",v2[p]);
        key = true;
    }

    print(++p);
}
int main(){
    int i;
    scanf("%d",&n);
    for( i = 0 ; i < n ; i++)scanf("%d",&in[i]);
    for( i = 0 ; i < n ; i++)scanf("%d",&pos[i]);
    Tree *root =buildTree(0,n-1,0,n-1);
    printLevelTree1(root);
    printLevelTree2(root);
    printf("%d",v1[0]);
    print(1);

    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{(队列最大存储量)} $$
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值