PAT甲级 -- 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

我的思路:

1. 建树,加一个变量level,开一个vector<int> v[1000], v[level]表示第level层的元素,一开始level为0,每一次level+1。

2. 之后之字形输出 

#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;

int n;
vector<int> inorder, postorder;
vector<int> v[10000];

void preBuild(int inl, int inr, int postRoot, int level){
	if(inl > inr)  return;
	int i = inl;
	while(inl < inr && postorder[postRoot] != inorder[i]) i++;
	v[level].push_back(inorder[i]);
	preBuild(inl, i-1, postRoot-1+i-inr,level+1);
	preBuild(i+1,inr, postRoot-1, level+1);
}

int main(){
	scanf("%d", &n);
	inorder.resize(n), postorder.resize(n);
	for(int i = 0; i < n; i++) scanf("%d", &inorder[i]);
	for(int i = 0; i < n; i++) scanf("%d", &postorder[i]);
	preBuild(0,n-1,n-1,0);
	printf("%d", v[0][0]);
	for (int i = 1; i < 35; i++){
		if (i % 2 == 1){ 
			for(int j = 0; j < v[i].size(); j++){
				printf(" %d",v[i][j]);
				
			}
						
		}else{
			for (int j = v[i].size()-1; j >= 0; j--){
				printf(" %d",v[i][j]);
			}
			
		}

		
	}
	
	return 0;
}

 

<think>好的,我现在需要帮助用户理解二叉树的Z字形遍历算法。首先,我得回忆一下这个算法的基本思路。Z字形遍历,也就是按层交替改变遍历方向,比如第一层从左到右,第二层从右到左,以此类推。这样的话,每一层的节点访问顺序会交替变化,形成锯齿形或者Z字形的路径。 接下来,我应该考虑如何实现这个算法。通常,二叉树的层次遍历会用到队列(BFS),但是Z字形遍历需要在不同层改变方向。所以可能需要一个标记来指示当前层的方向,并且在处理每层节点时根据方向决定如何存储结果。比如,当方向是从左到右时,直接添加节点值到结果列表;当方向是从右到左时,可能需要将节点值插入到结果列表的开头,或者先收集节点值再反转。 不过,用户提到了引用[2]中的内容,里面提到了使用BFS,并且在不同层采用不同的队列操作。比如,左到右时使用FIFO,添加元素到队尾;右到左时使用FILO,添加元素到队头。这可能涉及到双端队列(deque)的使用,这样可以在队头或队尾添加元素。例如,处理当前层节点时,如果是左到右方向,那么子节点按左孩子、右孩子的顺序添加到队尾;如果是右到左方向,子节点按右孩子、左孩子的顺序添加到队头。这样可以保证下一层的访问顺序正确。 然后,我需要确认算法的步骤。大致流程是: 1. 初始化队列,将根节点加入队列。 2. 进入循环,直到队列为空。 3. 记录当前层的节点数量,处理当前层的所有节点。 4. 根据当前层的方向,决定如何添加子节点到队列。 5. 切换方向,进入下一层。 同时,需要注意处理空节点的情况,确保不会将空子节点加入队列。 然后,考虑代码实现。用户可能希望看到具体的代码示例,比如Python中使用deque来实现。例如,使用一个布尔变量标记当前方向,当方向为左到右时,正常处理;否则,反转当前层的值或者改变子节点的添加顺序。 另外,用户提供的引用[2]中提到,左到右时使用FIFO,添加元素到队尾;右到左时使用FILO,添加到队头。这意味着在右到左的情况下,添加子节点时可能要先右后左,并且插入到队列前端,这样下一层处理时就能保持正确的顺序。例如,当处理右到左层时,节点从队列前端取出,子节点按右、左顺序插入到队列前端,这样下一层的处理顺序就会是左到右,因为队列中的顺序是左、右,所以取出时会是左先,右后,从而形成交替。 不过,这种方法可能需要不同的数据结构操作,比如在Python中,deque的appendleft方法可以用于前端添加。例如,在右到左方向时,子节点先右后左,插入到队列的前端,这样下一层处理时,节点顺序会是左、右,从而左先被处理,实现方向的切换。 现在,我需要将这些思路整理成一个清晰的步骤说明,并给出代码示例。同时,确保代码符合用户的要求,比如正确使用队列,处理方向切换,以及节点的添加顺序。 另外,要注意边界条件,比如根节点为空的情况,以及每一层处理完毕后方向变量的切换。 最后,生成相关问题,可能需要包括算法的时间复杂度、空间复杂度,如何用其他数据结构实现,或者与其他遍历方法的比较等。</think>### 二叉树的Z字形遍历算法(Binary Tree Zigzag Level Order Traversal) Z字形遍历要求按层交替改变节点访问方向(左→右、右→左交替),形成锯齿形路径。其核心是通过**广度优先搜索(BFS)**结合**双端队列(deque)**实现方向控制。 --- #### **算法步骤** 1. **初始化队列和方向标记** - 使用队列存储当前层的节点。 - 定义布尔变量 `left_to_right` 标记方向(初始为`True`,表示第一层左→右)。 2. **逐层遍历** - 循环处理队列中的节点,直到队列为空。 - 根据当前方向标记,决定如何将子节点加入队列: - **左→右方向**:子节点按左→右顺序加入队尾(FIFO),保证下一层按正常顺序访问[^2]。 - **右→左方向**:子节点按右→左顺序加入队头(FILO),保证下一层按反向顺序访问[^2]。 3. **收集结果并切换方向** - 每层遍历完成后,将节点值加入结果列表,并切换方向标记。 --- #### **Python代码实现** ```python from collections import deque def zigzag_level_order(root): 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. **方向控制** - 使用 `left_to_right` 标记方向,通过 `current_level` 的插入方式(`append`或`appendleft`)实现值的正向或反向存储。 2. **子节点入队逻辑** - 无论当前方向如何,子节点始终按左→右顺序加入队列尾部。这是因为队列的FIFO特性保证了下一层的节点顺序正确,而当前层的结果方向由 `current_level` 的插入方式决定。 3. **时间复杂度** - $O(N)$,每个节点仅被访问一次,$N$为节点总数。 --- #### **示例** 对二叉树: ``` 3 / \ 9 20 / \ 15 7 ``` Z字形遍历结果为: $$[[3], [20,9], [15,7]]$$ ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值