【PAT】1102. Invert a Binary Tree (25)【二叉树的中序遍历和层次遍历】

本文介绍了一个编程挑战,即如何在给定的二叉树结构中实现树的反转,包括层次遍历和中序遍历的输出。通过具体的输入输出示例,文章详细解释了解题思路和实现代码。

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

题目描述

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!

翻译:下面是来自Max Howell@twitter:
谷歌:我们90%的工程师使用你写的软件(Homebrew),但是你不能在白板上反转一个二叉树,所以滚蛋。
现在轮到你证明你可以反转一个二叉树了!

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.

翻译:每个输入文件包含一组测试数据。对于每组输入数据,第一行包括一个正整数N(≤10) ,代表树上的总节点数–假设所有节点被标记为0到N-1。接下来N行,每行包括一个节点从0到N-1,并且给出该节点的左孩子和右孩子目录。如果孩子不存在,该位置将会用‘-’来代替。任何一对孩子之间用空格隔开。

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


解题思路

保存节点的父亲,然后顺藤摸瓜找到根节点,再输出层次遍历和中序遍历。注意输出格式,和给出的样例进行比较。

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<vector> 
#include<queue>
#include<algorithm>
using namespace std;
int n;
int v[15][2];
int father[15];
int root=-1;
int findRoot(int node){
	if(father[node]==-1)return node;
	else findRoot(father[node]);
}
void levelOrder(int node){
	queue<int>q;
	q.push(root);
	int tflag=0;
	while(!q.empty()){
		int tmp=q.front();q.pop();
		if(!tflag)printf("%d",tmp),tflag=1;
		else printf(" %d",tmp);
		if(v[tmp][1]>=0)q.push(v[tmp][1]);
		if(v[tmp][0]>=0)q.push(v[tmp][0]);
	}
	printf("\n");
}
int ans[15],ccount=0;
int inOrder(int node){
	if(v[node][0]==-1);
	else inOrder(v[node][0]);
	ans[ccount++]=node;
	if(v[node][1]==-1);
	else inOrder(v[node][1]);
}
int main(){
	for(int i=0;i<15;i++)father[i]=-1;
	scanf("%d",&n);
	char a,b;
	for(int i=0;i<n;i++){
		scanf("\n%c %c",&a,&b);
		if(a=='-')v[i][0]=-1;
		else v[i][0]=a-'0',father[a-'0']=i;
		if(b=='-')v[i][1]=-1;
		else v[i][1]=b-'0',father[b-'0']=i;
	}
	root=findRoot(0);
	levelOrder(root);
	inOrder(root);
	for(int i=ccount-1;i>0;i--){
		printf("%d ",ans[i]);
	}
	printf("%d\n",ans[0]);
}
1. 创建二叉树 二叉树是一种树形结构,每个节点最多有两个子节点。我们可以通过递归的方式来创建二叉树。假设我们有一个数组arr表示二叉树的结构,-1表示空节点,其他数字表示节点的值。我们可以采用如下方式来创建二叉树: ```python class Node: def __init__(self, val): self.val = val self.left = None self.right = None def create_tree(arr, index): if index >= len(arr) or arr[index] == -1: return None root = Node(arr[index]) root.left = create_tree(arr, 2*index+1) root.right = create_tree(arr, 2*index+2) return root ``` 其中create_tree函数是递归创建二叉树的函数,参数arr表示数组,index表示当前节点在数组中的下标。如果当前节点为-1或者下标超出数组范围,则返回None,否则就创建一个节点,并将左子树右子树递归创建。 2.二叉树的前序遍历序列 前序遍历是指先遍历根节点,然后遍历左子树,最后遍历右子树。我们可以采用递归的方式来实现前序遍历。 ```python def preorder_traversal(root): if not root: return [] res = [root.val] res += preorder_traversal(root.left) res += preorder_traversal(root.right) return res ``` 其中preorder_traversal函数是递归实现前序遍历的函数,参数root表示根节点。如果根节点为空,则返回空列表。否则就先将根节点的值加入结果列表,然后递归遍历左子树右子树,并将结果合并。 3.二叉树的中序遍历序列 中序遍历是指先遍历左子树,然后遍历根节点,最后遍历右子树。我们可以采用递归的方式来实现中序遍历。 ```python def inorder_traversal(root): if not root: return [] res = inorder_traversal(root.left) res += [root.val] res += inorder_traversal(root.right) return res ``` 其中inorder_traversal函数是递归实现中序遍历的函数,参数root表示根节点。如果根节点为空,则返回空列表。否则就先递归遍历左子树,然后将根节点的值加入结果列表,最后递归遍历右子树,并将结果合并。 4.二叉树的后序遍历序列 后序遍历是指先遍历左子树,然后遍历右子树,最后遍历根节点。我们可以采用递归的方式来实现后序遍历。 ```python def postorder_traversal(root): if not root: return [] res = postorder_traversal(root.left) res += postorder_traversal(root.right) res += [root.val] return res ``` 其中postorder_traversal函数是递归实现后序遍历的函数,参数root表示根节点。如果根节点为空,则返回空列表。否则就先递归遍历左子树右子树,然后将根节点的值加入结果列表,并将结果合并。 5.二叉树层次遍历序列 层次遍历是指按照树的层次遍历节点。我们可以采用队列来实现二叉树层次遍历。 ```python def level_order_traversal(root): if not root: return [] res = [] queue = [root] while queue: cur_level = [] for i in range(len(queue)): node = queue.pop(0) cur_level.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) res.append(cur_level) return res ``` 其中level_order_traversal函数是实现二叉树层次遍历的函数,参数root表示根节点。如果根节点为空,则返回空列表。否则就先将根节点加入队列,然后依次将队列中的节点取出来,并将它们的左子树右子树加入队列,直到队列为空。 6. 计算二叉树的深度 二叉树的深度是指从根节点到叶子节点的最长路径长度。我们可以采用递归的方式来计算二叉树的深度。 ```python def tree_depth(root): if not root: return 0 left_depth = tree_depth(root.left) right_depth = tree_depth(root.right) return max(left_depth, right_depth) + 1 ``` 其中tree_depth函数是递归实现计算二叉树深度的函数,参数root表示根节点。如果根节点为空,则返回0。否则就递归计算左子树右子树的深度,并取最大值加1。 7. 统计二叉树中叶子结点的个数 叶子节点是指没有子节点的节点。我们可以采用递归的方式来统计二叉树中叶子节点的个数。 ```python def count_leaf_node(root): if not root: return 0 if not root.left and not root.right: return 1 return count_leaf_node(root.left) + count_leaf_node(root.right) ``` 其中count_leaf_node函数是递归实现统计叶子节点个数的函数,参数root表示根节点。如果根节点为空,则返回0。否则就判断当前节点是否为叶子节点,如果是则返回1,否则递归计算左子树右子树的叶子节点个数,并将它们相加。 8. 判断两棵树是否相等 判断两棵树是否相等,需要对两棵树进行遍历,并比较每个节点的值是否相等。我们可以采用递归的方式来判断两棵树是否相等。 ```python def is_same_tree(p, q): if not p and not q: return True if not p or not q: return False if p.val != q.val: return False return is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right) ``` 其中is_same_tree函数是递归实现判断两棵树是否相等的函数,参数pq分别表示两棵树的根节点。如果两棵树的根节点都为空,则返回True;如果其中有一棵树的根节点为空,则返回False;否则就比较两棵树的根节点的值是否相等,然后递归比较左子树右子树。 9. 交换二叉树中每个结点的左孩子右孩子 交换二叉树中每个节点的左孩子右孩子,可以采用递归的方式来实现。 ```python def invert_tree(root): if not root: return None root.left, root.right = root.right, root.left invert_tree(root.left) invert_tree(root.right) return root ``` 其中invert_tree函数是递归实现交换二叉树中每个节点的左孩子右孩子的函数,参数root表示根节点。如果根节点为空,则返回None;否则就先交换根节点的左孩子右孩子,然后递归交换左子树右子树。 10. 复制二叉树 复制一棵二叉树,可以采用递归的方式来实现。 ```python def copy_tree(root): if not root: return None new_root = Node(root.val) new_root.left = copy_tree(root.left) new_root.right = copy_tree(root.right) return new_root ``` 其中copy_tree函数是递归实现复制二叉树的函数,参数root表示根节点。如果根节点为空,则返回None;否则就先创建一个新节点并赋值为原节点的值,然后递归复制左子树右子树,并将它们赋值给新节点的左孩子右孩子。最后返回新根节点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值