1102. Invert a Binary Tree (25)【二叉树】——PAT (Advanced Level) Practise

本文介绍了一道经典的二叉树题目——翻转二叉树,并提供了完整的代码实现。通过输入节点及其左右子节点信息,文章展示了如何进行层序与中序遍历,并输出翻转后的二叉树。

题目信息

1102. Invert a Binary Tree (25)

时间限制400 ms
内存限制65536 kB
代码长度限制16000 B
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

解题思路

二叉树遍历

AC代码

#include <cstdio>
#include <vector>
#include <set>
using namespace std;
vector<int> level[15];
vector<int> inorder;
int get(){
    char s[10];
    scanf("%s", s);
    if (s[0] == '-') return -1;
    int a;
    sscanf(s, "%d", &a);
    return a;
}
int L[15], R[15];
void inOrder(int root){
    if (R[root] != -1) inOrder(R[root]);
    inorder.push_back(root);
    if (L[root] != -1) inOrder(L[root]);
}
void levelOrder(int root, int lv){
    level[lv].push_back(root);
    if (R[root] != -1) levelOrder(R[root], lv + 1);
    if (L[root] != -1) levelOrder(L[root], lv + 1);
}
int main()
{
    int n;
    scanf("%d", &n);
    set<int> st;
    for (int i = 0; i < n; ++i){
        st.insert(i);
    }
    for (int i = 0; i < n; ++i){
        L[i] = get();
        R[i] = get();
        if (L[i] != -1) st.erase(L[i]);
        if (R[i] != -1) st.erase(R[i]);
    }
    levelOrder(*st.begin(), 0);
    inOrder(*st.begin());
    printf("%d", *st.begin());
    for (int i = 1; i < 15; ++i){
        for (int j = 0; j < level[i].size(); ++j){
            printf(" %d", level[i][j]);
        }
    }
    printf("\n%d", inorder[0]);
    for (int i = 1; i < inorder.size(); ++i){
        printf(" %d", inorder[i]);
    }
    return 0;
}
<think>嗯,用户之前问的是如何用OpenCV绘制扇形区域,现在突然转向了cv2.invert函数的用法。看起来用户可能在进行图像处理时遇到了矩阵操作的需求,比如需要计算逆矩阵来进行几何变换或其他应用。 首先,用户提到的引用内容中提到了cv::invert函数,用于计算矩阵的逆,这可能和仿射变换相关,比如在之前的回答中提到了仿射变换的应用,用户可能想结合两者进行更复杂的图像处理操作。 需要确认cv2.invert的具体用法,包括参数、返回值以及不同标志的区别。用户可能需要知道如何正确使用这个函数,特别是在处理图像变换时的实际应用场景,比如在计算仿射变换的逆变换时使用。 另外,用户提供的引用中有C#的示例代码,但用户现在使用的是Python的OpenCV,所以需要将示例转换成Python的语法,比如使用cv2.invert而不是Cv2.Invert。 还要注意函数返回两个值,在Python中返回值是一个元组,包含retval和逆矩阵,而C++中是通过参数返回的。需要明确说明这一点,避免用户混淆。 用户可能还关心如何处理奇异矩阵的情况,即不可逆的情况,这时候函数会返回0,并且逆矩阵可能无效,需要提醒用户注意检查返回值。 此外,结合之前的扇形绘制,用户可能在尝试进行一些几何变换,比如先进行仿射变换然后逆变换恢复原图,这时候可能需要用到逆矩阵,所以示例中可以结合这样的场景,比如使用warpAffine和invert函数来演示应用。 需要提供不同标志的对比,比如DECOMP_LU和DECOMP_SVD,说明它们的适用场景,比如LU分解更高效但要求矩阵非奇异,而SVD适用于奇异矩阵但计算量大。 最后,确保代码示例正确,包括矩阵的创建、逆矩阵的计算以及可能的应用场景,帮助用户理解如何在实际项目中使用cv2.invert函数。</think>以下是对$cv2.invert$函数的详细说明及使用示例,结合OpenCV几何变换相关应用场景: ### 一、函数原型与参数解析 ```python retval, dst = cv2.invert(src, flags=cv2.DECOMP_LU) ``` | 参数 | 类型 | 说明 | |------|------|------| | `src` | 输入矩阵 | 必须是浮点型(CV_32F/CV_64F)的方阵 | | `flags` | 计算方式 | `cv2.DECOMP_LU`(默认) 或 `cv2.DECOMP_SVD` | | `retval` | 返回值 | 成功标志(0表示奇异矩阵)[^1] | | `dst` | 输出矩阵 | 计算得到的逆矩阵 | ### 二、典型应用场景 #### 1. 基础矩阵求逆(2x2矩阵) ```python import cv2 import numpy as np # 创建可逆矩阵 matrix = np.array([[4, 7], [2, 6]], dtype=np.float32) # 计算逆矩阵 ret, inv_matrix = cv2.invert(matrix) if ret != 0: print("逆矩阵:\n", inv_matrix) # 验证矩阵相乘结果(应近似单位矩阵) print("验证:\n", matrix @ inv_matrix) else: print("矩阵不可逆") ``` 输出结果: ``` 逆矩阵: [[ 0.6 -0.7] [-0.2 0.4]] 验证: [[1.0000000e+00 1.1920929e-07] [0.0000000e+00 1.0000000e+00]] ``` #### 2. 仿射变换逆运算(6x6矩阵) ```python # 生成随机仿射矩阵 affine_matrix = np.array([[0.8, -0.3, 50], [0.4, 0.6, -30]], dtype=np.float32) # 扩展为3x3齐次矩阵 M = np.vstack([affine_matrix, [0, 0, 1]]) # 计算逆变换矩阵 ret, M_inv = cv2.invert(M) if ret != 0: # 提取有效仿射参数(前两行) inv_affine = M_inv[:2] print("逆仿射矩阵:\n", inv_affine) else: print("变换矩阵不可逆") ``` ### 三、关键参数对比 | 标志位 | 算法 | 计算量 | 适用场景 | |--------|------|--------|----------| | `cv2.DECOMP_LU` | LU分解 | 较小 | 非奇异矩阵(推荐常规使用)[^3] | | `cv2.DECOMP_SVD` | 奇异值分解 | 较大 | 奇异矩阵或病态矩阵 | ### 四、几何变换综合应用 结合仿射变换的逆运算实现图像复原: ```python img = cv2.imread('input.jpg') rows, cols = img.shape[:2] # 生成仿射变换矩阵 M = cv2.getRotationMatrix2D((cols/2, rows/2), 30, 0.8) # 应用变换 warped = cv2.warpAffine(img, M, (cols, rows)) # 计算逆变换 ret, M_inv = cv2.invert(M, flags=cv2.DECOMP_LU) if ret != 0: # 逆向变换复原图像 restored = cv2.warpAffine(warped, M_inv[:2], (cols, rows)) cv2.imshow('Restored', restored) ``` ### 五、注意事项 1. 输入矩阵必须是方阵且数据类型为`CV_32F`或`CV_64F` 2. 对奇异矩阵(行列式接近0)应检查返回值`retval` 3.Python接口中返回的是`(retval, inverse_matrix)`元组 4. SVD模式会返回伪逆矩阵,但精度可能降低[^1]
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值