【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!

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

题意:将二叉树反转(即左右节点交换),然后给出层序遍历和中序遍历的结果。

分析:层序遍历用队列即可,中序遍历用栈来实现。不难,但是要仔细。

#include <iostream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;

struct node{
	node(){
		left = -1;
		right = -1;
		father = -1;
		level = 0;
	}
	int index;
	int left;
	int right;
	int father;
	int level;
};

int main(int argc, char** argv) {
	int n, i;
	scanf("%d",&n);
	getchar();
	vector<node> tree(n);
	char L, R;
	int left , right;
	for(i=0; i<n; i++){
		tree[i].index = i;
		scanf("%c %c",&L, &R);
		getchar();
		if(isdigit(L)){
			left = L - '0';
			tree[i].right = left ;
			tree[left].father = i;
		}
		if(isdigit(R)){
			right = R - '0';
			tree[i].left = right;
			tree[right].father = i;
		}		
	}
	
	int root;
	for(i=0; i<n; i++){
		if(tree[i].father == -1){		 
			root = i;
			break;
		}
	}
	
	queue<int> que;
	int level, index;
	que.push(root);
	printf("%d",root);
	bool first = false;
	node tmpNode;
	while(!que.empty()){	
		tmpNode = tree[que.front()];
		if(!first){
			first = true;
		}else{
			printf(" %d",que.front());
		}
		level = tmpNode.level;
		left = tmpNode.left;
		right = tmpNode.right;
		if(left != -1){
			que.push(left);
		}
		if(right != -1){
			que.push(right);
		}
		que.pop();
	}
	printf("\n");
		
	stack<int> sta;
 	sta.push(root); 
 	int cnt = 0;
 	while(!sta.empty()){
 		index = sta.top();
		tmpNode = tree[index];
		left = tmpNode.left;
		while(left != -1){
			tree[index].left = -1;
			sta.push(left);
			tmpNode = tree[left];
			index = tmpNode.index;
			left = tmpNode.left;		 
		} 
 		cnt++;
 		if(cnt==n){
 			printf("%d\n",sta.top());
		}else{
			printf("%d ",sta.top());
		}
		sta.pop();
	    if(tmpNode.right != -1){
	    	sta.push(tmpNode.right);
		}		 	
	}
	
	return 0;
}

另一种写法:

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

struct node{
	node(){
		fa = -1;
		left = -1;
		right = -1;
	}
	int id, fa, left, right;
};
vector<node> tree;

void inOrder(int r, vector<int> &vec){
	if(tree[r].right != -1){
		inOrder(tree[r].right,vec);
	}
	vec.push_back(r);
	if(tree[r].left!=-1){
		inOrder(tree[r].left,vec);
	}	
}

void levelOrder(int r, vector<int> &vec){
	queue<node> que;
	que.push(tree[r]);
	while(!que.empty()){
		node n = que.front();
		if(n.right!= -1){
			que.push(tree[n.right]);
		}
		if(n.left!=-1){
			que.push(tree[n.left]);
		}
		vec.push_back(n.id);
		que.pop();
	}
}

void show(vector<int> &vec){
	int i;
	for(i=0; i<vec.size(); i++){
		if(i==0){
			printf("%d",vec[i]);
		}else{
			printf(" %d",vec[i]);
		}
	}	
	printf("\n");
}

int main(int argc, char** argv) {
	int N;
	scanf("%d",&N);
	getchar();
	int i;
	tree.resize(N);
	char a, b;
	for(i=0; i<N; i++){
		tree[i].id = i;
		scanf("%c %c",&a,&b);
		getchar();
		if(isdigit(a)){
			tree[a-'0'].fa = i;
			tree[i].left = a-'0';
		}
		if(isdigit(b)){
			tree[b -'0'].fa = i;
			tree[i].right = b-'0';
		}
	}
	int root;
	for(i=0; i<N; i++){
		if(tree[i].fa==-1){
			root = i;
			break;
		}
	}
	vector<int> level;
	levelOrder(root, level);
	show(level);
	
	vector<int> vec;
	inOrder(root,vec);
	show(vec);
	
	return 0;
}









<think>好的,我现在需要回答用户关于gmpy2.invert函数的用法以及如何计算模逆元的问题。首先,我要回忆一下模逆元的基本概念。模逆元指的是在模运算中,找到一个数x,使得$a \times x \equiv 1 \mod m$。也就是说,a和x的乘积在模m下等于1。这种情况下,x就是a的模m逆元,记作$a^{-1} \mod m$。 接下来,我需要确认gmpy2库中的invert函数的具体用法。根据我的知识,gmpy2是一个Python库,提供了高精度计算的功能,特别是在处理大整数时非常有用。gmpy2.invert函数的作用应该就是计算这样的模逆元。函数的参数可能有两个,分别是a和m,返回的是a在模m下的逆元。 但是,可能存在一些条件。比如,a和m必须互质,也就是它们的最大公约数是1,否则逆元不存在。如果用户传入的参数e和L不互质,那么调用invert函数可能会抛出错误或者返回None,这需要验证。 接下来,我需要考虑如何给出一个具体的例子。比如,假设e=3,L=20,首先检查gcd(3,20)是否为1。3和20的最大公约数是1,所以存在逆元。这时候调用gmpy2.invert(3,20)应该返回7,因为3*7=21,21 mod 20等于1。 然后,我需要考虑如何处理逆元不存在的情况。例如,如果e=2,L=4,因为gcd(2,4)=2≠1,所以逆元不存在。这时候调用invert函数应该会报错或者返回None。需要提醒用户在使用前检查参数是否互质,或者使用try-except块处理异常。 此外,可能还需要比较gmpy2.invert与其他方法计算模逆元的方式,比如使用扩展欧几里得算法手动实现,或者使用Python内置的pow函数(在Python 3.8+中pow(a, -1, m)也可以计算逆元)。但gmpy2的优势在于处理非常大的整数,比如在RSA加密中常见的超大数,这时候gmpy2的效率更高。 然后,我需要确保回答中正确应用了用户提到的格式要求:行内数学公式用$...$,独立公式用$$...$$,并且正确引用提供的参考文献。根据用户给出的引用,引用[1]提到了计算$P^k(x)=Q$的方法,可能与模幂运算有关,但不确定是否直接相关。引用[2]和[3]看起来与当前问题无关,但可能需要寻找是否有间接关联。例如,引用[1]中的指数和对数运算可能与模运算中的快速幂算法有关,但可能需要明确如何联系到逆元的计算。不过,可能用户提供的引用中有误,或者需要忽略不相关的引用。 在示例代码部分,用户可能希望有一个使用gmpy2.invert的实际Python代码示例,包括正确的参数传递和结果验证。例如: ```python import gmpy2 e = 3 L = 20 try: inverse = gmpy2.invert(e, L) print(f"The modular inverse of {e} mod {L} is {inverse}") except Exception as e: print(f"Error: {e}") ``` 此外,用户可能需要了解应用场景,比如在RSA算法中,计算私钥指数d时需要使用模逆元,即d ≡ e^{-1} mod φ(n),其中φ(n)是欧拉函数。这时候,gmpy2.invert可以高效地计算这个d值,尤其是当e和φ(n)都是非常大的数时。 最后,我需要生成相关问题,可能包括如何处理参数不互质的情况,gmpy2.invert与其他方法的比较,模逆元在密码学中的应用,或者如何手动实现扩展欧几里得算法来计算逆元等。</think>### gmpy2.invert函数用法及模逆元计算 #### 1. 函数功能 `gmpy2.invert(a, m)` 用于计算整数 $a$ 在模 $m$ 下的**模逆元**,即寻找整数 $x$ 满足: $$a \times x \equiv 1 \mod m$$ 若逆元存在,则返回 $x$;否则抛出异常[^1]。 #### 2. 使用条件 - **互质要求**:$a$ 和 $m$ 必须互质(即 $\gcd(a, m) = 1$),否则逆元不存在。 - **参数类型**:$a$ 和 $m$ 需为整数,支持大整数运算。 #### 3. 示例代码 ```python import gmpy2 # 示例1:逆元存在 e = 3 L = 20 result = gmpy2.invert(e, L) print(f"{e}^-1 mod {L} = {result}") # 输出:3^-1 mod 20 = 7 (3*7=21 ≡1 mod20) # 示例2:逆元不存在(触发异常) try: gmpy2.invert(2, 4) except gmpy2.DivisionByZeroError: print("逆元不存在,因gcd(2,4)=2 ≠1") ``` #### 4. 应用场景 - **密码学**:如RSA算法中计算私钥指数 $d$,满足 $d \equiv e^{-1} \mod \phi(n)$。 - **数论计算**:解线性同余方程 $ax \equiv b \mod m$。 #### 5. 对比其他方法 | 方法 | 特点 | |--------------------|----------------------------------------------------------------------| | `gmpy2.invert` | 高效处理大整数,直接返回结果或报错 | | `pow(a, -1, m)` | Python内置方法(3.8+),要求 $\gcd(a,m)=1$,否则引发 `ValueError` | | 扩展欧几里得算法 | 手动实现,可同时计算 $\gcd(a,m)$ 和逆元,适合教学或兼容性要求 | ####
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值