PAT 甲级1127 ZigZagging on a Tree (30分)

本文介绍了一种特殊的二叉树遍历方法——Z字遍历,通过中序和后序遍历序列构建二叉树,然后使用双栈技巧实现从根节点开始的交错左右层次遍历。

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
题目大意:给出中序和后序遍历建立二叉树然后采用Z字遍历该二叉树
主要思路:步骤1.根据中序和后序建立二叉树:
后序最后面的结点为根节点然后再中序找到根节点的位置,其左侧就为左子树右侧就为右字树依次递归进行;
步骤2.根据二叉树进行Z字遍历:考虑第一层从右往左第二层从左往右很容易想到利用两个堆栈来实现,第一个堆栈出栈顺序相当于从右往左输出,为了使下一层从左往右输出,我们需要先将右孩子入到第二个栈再将左孩子入到第二个栈,依次进行就可以达到Z字遍历的效果。
AC代码:

#include<algorithm>
#include<iostream>
#include<cstdio>
#include<stack>
#include<queue>
using namespace std;
const int maxn=31;
struct Node{
Node *leftchild,*rightchild;
int data;
};
int n;
int in[maxn],post[maxn];
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(k=inl;k<=inr;k++){
if(in[k]==post[postr])
break;
}
int numl=k-inl;//左子书数
root->leftchild=Create(postl,postl+numl-1,inl,k-1);
root->rightchild=Create(postl+numl,postr-1,k+1,inr);
return root;
}
void ZigZagging (Node *root){
stack<Node *>st,st1;
printf("%d",root->data);
if(root->rightchild!=NULL){
    st.push(root->rightchild);
}
if(root->leftchild!=NULL){
   st.push(root->leftchild);
}
while(!st.empty()||!st1.empty())
{while(!st.empty()){
    Node* now=st.top();
    printf(" %d",now->data);
    st.pop();
    if(now->leftchild!=NULL){
        st1.push(now->leftchild);
    }
    if(now->rightchild!=NULL){
        st1.push(now->rightchild);
    }
}
while(!st1.empty()){
    Node* now=st1.top();
    printf(" %d",now->data);
  st1.pop();
    if(now->rightchild!=NULL){
        st.push(now->rightchild);
    }
    if(now->leftchild!=NULL){
        st.push(now->leftchild);
    }

}
}}
int main(){
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]);
}
Node *root=Create(0,n-1,0,n-1);
ZigZagging(root);
system("pause");
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、付费专栏及课程。

余额充值