北大算法分析和复杂性理论-2017算法课第一次作业E:二叉树的操作

本文介绍了一个基于二叉树的数据结构实现,包括节点交换和查找最左节点的功能。通过具体的C++代码示例,展示了如何进行节点的父子关系调整及如何找到从指定节点开始的最左侧节点。

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

http://algorithm.openjudge.cn/algorithma/E/

题意理解:复杂度允许暴力做,记不记录父亲是谁都可以,注意用指针的话别re。

急转弯:无

算法:无

数据结构:二叉树(的遍历)

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

const int maxn = 100 + 10;

struct node{
    int id, lson, rson, fa;
};
node t[maxn];
int n, m;

int getl(int u) {
    if(t[u].lson == -1) return u;
    return getl(t[u].lson);
}

int main() {
    int T;
    scanf("%d", &T);
    for(int _ = 0; _ < T; _++) {
        scanf("%d%d", &n, &m);
        memset(t, 0, sizeof(t));
        for(int i = 0; i < n; i++){
            int x, y, z;
            scanf("%d%d%d", &x, &y, &z);
            t[x].lson = y;
            t[x].rson = z;
            t[z].fa = x;
            t[y].fa = x;
        }
        for(int i = 0; i < m; i++) {
            int type, x, y;
            scanf("%d", &type);
            if(type == 1) {
                scanf("%d%d", &x, &y);
                int xfa = t[x].fa, yfa = t[y].fa;
                t[x].fa = yfa;
                t[y].fa = xfa;
                int *xpos;
                int *ypos;
                if(t[xfa].lson == x) {
                    xpos = &t[xfa].lson;
                } else{
                    xpos = &t[xfa].rson;
                }
                if(t[yfa].lson == y) {
                    ypos = &t[yfa].lson;
                } else{
                    ypos = &t[yfa].rson;
                }
                int tx = (*xpos), ty = (*ypos);
                (*xpos) = ty;
                (*ypos) = tx;
            } else{
                scanf("%d", &x);
                printf("%d\n", getl(x));
            }
        }
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值