算法分析与复杂性原理 第一次上机 二叉树的操作

来源:互联网 发布:etl算法 编辑:程序博客网 时间:2024/05/16 12:29

总时间限制: 
1000ms 
内存限制: 
65535kB
描述

给定一棵二叉树,在二叉树上执行两个操作:
1. 节点交换
把二叉树的两个节点交换。

2. 前驱询问
询问二叉树的一个节点对应的子树最左边的节点。

输入
第一行输出一个整数t(t <= 100),代表测试数据的组数。

对于每组测试数据,第一行输入两个整数n m,n代表二叉树节点的个数,m代表操作的次数。

随后输入n行,每行包含3个整数X Y Z,对应二叉树一个节点的信息。X表示节点的标识,Y表示其左孩子的标识,Z表示其右孩子的标识。

再输入m行,每行对应一次操作。每次操作首先输入一个整数type。

当type=1,节点交换操作,后面跟着输入两个整数x y,表示将标识为x的节点与标识为y的节点交换。输入保证对应的节点不是祖先关系。

当type=2,前驱询问操作,后面跟着输入一个整数x,表示询问标识为x的节点对应子树最左的孩子。

1<=n<=100,节点的标识从0到n-1,根节点始终是0.
m<=100
输出
对于每次询问操作,输出相应的结果。
样例输入
25 50 1 21 -1 -12 3 43 -1 -14 -1 -12 01 1 22 01 3 42 23 20 1 21 -1 -12 -1 -11 1 22 0
样例输出
1342


#include <iostream>#include <stdio.h>using namespace std;int tree[105][2];int xFather, yFather;bool xIsLeft, yIsLeft;int getLeft(int x){    if(tree[x][0] == -1)        return x;    else        return getLeft(tree[x][0]);}void swapXY(int root, int x, int y){    if(root == -1)        return;    if(xFather != -1 && yFather != -1)    {        if(xIsLeft)            tree[xFather][0] = y;        else            tree[xFather][1] = y;        if(yIsLeft)            tree[yFather][0] = x;        else            tree[yFather][1] = x;        return;    }    if(tree[root][0] == x)    {        xFather = root;        xIsLeft = true;    }    if(tree[root][1] == x)    {        xFather = root;        xIsLeft = false;    }    if(tree[root][0] == y)    {        yFather = root;        yIsLeft = true;    }    if(tree[root][1] == y)    {        yFather = root;        yIsLeft = false;    }    swapXY(tree[root][0], x, y);    swapXY(tree[root][1], x, y);}int main(){    int t;    cin >> t;    for (int i = 0; i < t; i++)    {        int n, m;        cin >> n >> m;        for(int j = 0; j < n; j++)        {            int x, y, z;            cin >> x >> y >> z;            tree[x][0] = y;            tree[x][1] = z;        }        for(int k = 0; k < m; k++)        {            int type, x, y;            cin >> type;            switch(type)            {            case (1):                cin >> x >> y;                xFather = yFather = -1;                swapXY(0, x, y);                break;            case(2):                cin >> x;                cout << getLeft(x) << endl;            }        }    }    return 0;}






阅读全文
0 0