PAT (Advanced Level) 1102 Invert a Binary Tree (25 分)

本文详细解析了如何通过编程实现二叉树的翻转,包括输入输出规范、层次遍历与中序遍历的实现,以及核心代码示例。通过对题目背景的介绍和具体算法的讲解,帮助读者理解并掌握二叉树翻转的基本原理。

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

1102 Invert a Binary Tree (25 分)

The following is from Max Howell @twitter:

Google: 90% of our engineers use the software you wrote (Homebrew), but you can't invert a binary tree on a whiteboard so fuck off.

Now it’s your turn to prove that YOU CAN invert a binary tree!

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤10) which is the total number of nodes in the tree – and hence the nodes are numbered from 0 to N−1. Then N lines follow, each corresponds to a node from 0 to N−1, and gives the indices of the left and right children of the node. If the child does not exist, a - will be put at the position. Any pair of children are separated by a space.

Output Specification:

For each test case, print in the first line the level-order, and then in the second line the in-order traversal sequences of the inverted tree. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.

Sample Input:

8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

Sample Output:

3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1

Code:

#include <iostream>
#include <vector>
#include <queue>
#pragma warning(disable:4996)
using namespace std;

struct Node
{
	int l, r;
	Node() { l = r = -1; }
};

vector<Node> tree; // 找root后完成层次遍历和中序遍历

void levelOrder(int root)
{
	queue<int> q;
	q.push(root);
	int cnt = 0;
	while (!q.empty())
	{
		int t = q.front();
		q.pop();
		cnt++;
		printf("%d%c", t, (cnt == tree.size() ? '\n' : ' '));
		if (tree[t].l != -1) q.push(tree[t].l);
		if (tree[t].r != -1) q.push(tree[t].r);
	}
}

int in_cnt = 0;
void inOrder(int root)
{
	if (root == -1)
		return;
	inOrder(tree[root].l);
	in_cnt++;
	printf("%d%c", root, (in_cnt == tree.size() ? '\n' : ' '));
	inOrder(tree[root].r);
}

int main()
{
	int n;
	scanf("%d", &n);
	tree.resize(n);
	vector<int> isRoot(n, 1);
	for (int i = 0; i < n; i++)
	{
		char l, r;
		getchar();
		scanf("%c %c", &l, &r);
		if (r != '-')
		{
			tree[i].l = r - '0';
			isRoot[r - '0'] = 0;
		}
		if (l != '-')
		{
			tree[i].r = l - '0';
			isRoot[l - '0'] = 0;
		}
	}
	int root;
	for (int i = 0; i < isRoot.size(); i++)
		if (isRoot[i]) root = i;
	levelOrder(root);
	inOrder(root);
	return 0;
}

思路:

注意点:scanf("%c", &ch)的时候,不会自动过滤\n 和 ‘ ’(即回车和空格)

<think>好的,我需要解释用户提供的这个反转二叉树的函数。首先,我得理解这个函数的结构和作用。函数名为invert_tree,参数是root,看起来是一个二叉树的节点。 首先,函数检查root是否存在(if root:),如果存在,就交换它的左右子节点。这里用到了递归,因为对左右子节点也调用了invert_tree。最后返回root。整个过程应该是将每个节点的左右子树都交换,从而反转整个二叉树。 接下来,我需要考虑如何逐步解释这个函数。可能需要从递归的基本思想入手,解释基线条件和递归步骤。基线条件是当root为空时,直接返回。递归步骤则是先处理左右子树,再交换它们的位置。 另外,要说明这个算法的时间复杂度和空间复杂度。因为是遍历每个节点一次,时间复杂度应该是O(n),n是节点数量。空间复杂度取决于递归的深度,最坏情况下(树完全不平衡)是O(n),平均情况下(平衡树)是O(log n)。 还需要提到应用场景,比如镜像二叉树、某些算法问题中的需求,比如判断对称二叉树可能需要先反转再比较。 可能还需要对比其他实现方式,比如使用迭代法(队列或栈)来反转二叉树,但用户提供的代码是递归实现,所以重点在递归上。 要注意代码中的交换操作是在递归调用之后还是之前。这里代码是root.left和root.right别赋值为反转后的右子树和左子树,所以是后序遍历,先处理子节点再交换。这样是否正确?是的,因为先递归反转左右子树,再交换它们的引用,这样整个树就被反转了。 可能还要给出一个例子,比如输入一个树的结构,然后展示反转后的结果,帮助用户理解。 此外,需要指出可能的错误情况,比如如果节点没有left或right属性是否会出错,但函数中只要root非空就会执行交换,所以假设节点结构正确,有left和right属性。如果传入的root节点不符合这个结构,可能会抛出错误,但函数本身没有处理这些情况,属于前提条件。 最后,总结这个函数的用途和实现方法,强调递归的简洁性和效率。</think>```markdown # 二叉树反转函数解析:递归实现详解 ## 一、函数定义与核心逻辑 ```python def invert_tree(root): if root: # 基线条件:节点存在时操作 # 后序遍历递归 + 交换左右子树 root.left, root.right = invert_tree(root.right), invert_tree(root.left) return root # 返回当前子树的新根节点 ``` ## 二、算法执行流程解析 ### 2.1 递归过程解 1. **叶子节点**:直接交换左右空指针(实际无变化) 2. **单子树节点**: ``` 1 1 / \ => \ 2 ∅ 2 ``` 3. **完整子树节点**: ``` 1 1 / \ / \ 2 3 => 3 2 ``` ### 2.2 时间复杂度析 | 情况 | 时间复杂度 | 空间复杂度 | |-------------|----------|----------| | 平衡二叉树 | $O(n)$ | $O(\log n)$ | | 链状结构 | $O(n)$ | $O(n)$ | ## 三、执行示例演示 ### 原始树结构: ``` 4 / \ 2 7 / \ / \ 1 3 6 9 ``` ### 执行过程: 1. 反转左子树(2为根) - 反转1→保持 - 反转3→保持 - 交换1和3的父节点指针 2. 反转右子树(7为根) - 反转6→保持 - 反转9→保持 - 交换6和9的父节点指针 3. 交换根节点4的左右子树指针 ### 最终结果: ``` 4 / \ 7 2 / \ / \ 9 6 3 1 ``` ## 四、常见问题解答 ### Q1:如何处理空节点? - 函数通过`if root`判断自动过滤空节点,递归到叶子节点时自然终止 ### Q2:能否用迭代法实现? **层序遍历实现示例**: ```python def invert_tree_iterative(root): stack = [root] while stack: node = stack.pop() if node: node.left, node.right = node.right, node.left stack.append(node.left) stack.append(node.right) return root ``` ### Q3:算法应用场景 1. 创建镜像二叉树 2. 判断对称二叉树(需比较原树与镜像树) 3. 图形渲染中的场景翻转 4. 某些二叉树算法题的基础操作 ## 五、代码健壮性析 ### 5.1 优势特性 - 自动处理空指针 - 内存效率高(原地修改) - 代码简洁直观 ### 5.2 潜在风险 - 节点必须具有left/right属性 - 超深递归可能引发栈溢出(Python默认递归深度约1000层) ## 六、算法变体扩展 ### 带返回值统计的版本 ```python def invert_tree_with_count(root): if not root: return 0 left_count = invert_tree_with_count(root.left) right_count = invert_tree_with_count(root.right) root.left, root.right = root.right, root.left return left_count + right_count + 1 ``` 该实现通过后序遍历统计反转操作涉及的节点总数,展示了如何在基础算法上添加附加功能。 通过这种递归实现,我们以$O(n)$时间复杂度高效完成了二叉树的反转操作,这种模式也是处理树形结构的经典范式。 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值