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.
在这里插入图片描述

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.

本菜鸡只会用建树的方法做:建树->求每一层的节点顺序->分层从前往后或从后往前输出

#include<iostream>
#include<vector>
#include<queue>
using namespace std;
typedef struct node {
	int data, level;
	node *l, *r;
}*tree;
int n, post[40], in[40], depth = 0;
vector<int>res[40];
tree createT(int inS, int inE, int postS, int postE) {
	if (inS > inE)return NULL;
	tree t = new node();
	t->data = post[postE];
	int i;
	for (i = inS; i <= inE; i++) {
		if (in[i] == post[postE])break;
	}
	t->l = createT(inS, i - 1, postS, postS + i - 1 - inS);
	t->r = createT(i + 1, inE, postE + i - inE, postE - 1);
	return t;
}
void bfs(tree root) {
	queue<tree>q;
	q.push(root);
	root->level = 1;
	while (!q.empty()) {
		auto temp = q.front();
		if (temp->level > depth) {
			depth = temp->level;
		}
		q.pop();
		res[temp->level].push_back(temp->data);
		if (temp->l != NULL) {
			temp->l->level = temp->level + 1;
			q.push(temp->l);
		}
		if (temp->r != NULL) {
			temp->r->level = temp->level + 1;
			q.push(temp->r);
		}
	}
}
int main() {
	cin >> n;
	for (int i = 0; i < n; i++)cin >> in[i];
	for (int i = 0; i < n; i++)cin >> post[i];
	tree t = createT(0, n - 1, 0, n - 1);
	bfs(t);
	cout << res[1][0];
	for (int i = 2; i <= depth; i++) {
		if (i % 2 == 0) {
			for (int j = 0; j < res[i].size(); j++) {
				cout << " " << res[i][j];
			}
		}
		else if (i % 2 == 1) {
			for (int j = res[i].size() - 1; j >= 0; j--) {
				cout << " " << res[i][j];
			}
		}
	}
	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、付费专栏及课程。

余额充值