Method 1:
Applicable conditions of this method:
1.When we traverse the tree, we only need to find the child node from the parent node, and we don't need to find the parent node from the child node.
2. The tree built is a binary tree
Implementation code:
class Tree{
int value;//代表该点的权值
int left_son;//左儿子编号
int right_son;//右儿子编号
int leftSide_value;//连接左儿子的边的权值
int rightSide_value;//连接右儿子边的权值
}
Enter according to the title description. For
example, enter the node number node weight in turn, the left son number, the right son number, and the weight of the edge connecting the left son, connecting the weight of the right son edge
for(int i=1;i<=n;i++)//n代表节点的个数
{
num=sc.nextInt();
tree[num].value=sc.nextInt();
tree[num].left_son=sc.nextInt();
.......
}
Method 2:
Applicable conditions of this method:
1.When we traverse the tree, we only need to find the child node from the parent node, and we don't need to find the parent node from the child node.
2. This method makes up for a shortcoming of method 1. Method one is suitable for binary trees, not for trees with multiple child nodes, and this method can have multiple child nodes
Implementation code:
void add(int a, int b){
//表示a为父 b为子
edge[cnt] = b;
ne[cnt] = last[a];
last[a] = cnt++;
}
I believe that seeing this code is a bit dizzy. At the beginning, I was too. Look at the following search process.
We are looking at its storage structure. We queue the nodes in the order of input. Assuming that there is such a tree
number representing the order of input, we Show how the right side of the tree is connected (cnt represents the input order and not the real number, edge[cnt] is the real number)
So you can get the query code
for(int i=last[a];i>=1;i=ne[i])
Continually updated!