题目回顾
树上搜索
https://sim.csp.thusaac.com/contest/32/problem/2
C++满分题解
思路概述

接下来设计数据结构。存在对树的很多插入,剪枝操作,毋庸置疑用链表实现最为合适。 由于完成一次类别测试后,需要树结构的恢复,所以增加parent结点来快速完成剪枝后的拼接而不用从输入重塑树结构。
typedef struct treeNode
{
int index;
long long weight;
treeNode* child;
treeNode* lastChild;
treeNode* brother;
treeNode* prevBrother;
treeNode* parent;
int childID;
treeNode(long long weight, int index) {
this->weight = weight;
this->index = index;
this->parent = nullptr;
this->child = nullptr;
this->lastChild = nullptr;
this->brother = nullptr;
this->prevBrother = nullptr;
}
} tree;
treeNode* myTree[2010];
下面我们来实现程序框图里的抽象过程 。
根据输入构建树结构
首先通过第一、二行输入,初始化所有的结点的 index 和 weight,通过第三行输入来实现结点之间的连接,构建出一棵树。我们定义一个函数来实现两结点之间的链接,顺序遍历第三行输入就能把一整棵树连接出来。
void linkNodes(treeNode* parent, treeNode* child) {
child->parent = parent;
if (!parent->child) {
// 如果parent结点还没有孩子
parent->child = child;
parent->lastChild = child;
}
else
{
// 如果parent结点已经有了孩子
parent->lastChild->brother = child;
child->prevBrother = parent->lastChild;
parent->lastChild = child;
}
}

最低0.47元/天 解锁文章
527

被折叠的 条评论
为什么被折叠?



