我有一棵树的BFS
和DFS
遍历,如何从这些遍历中重建树?
例如:
BFS Traversal : 4 3 5 1 2 8 7 6
DFS Traversal : 4 3 1 7 2 6 5 8
那么树的结构将会如下所示:
4
/ \
3 5
/ \ \
2 1 8
| |
6 7
我有一棵树的BFS
和DFS
遍历,如何从这些遍历中重建树?
例如:
BFS Traversal : 4 3 5 1 2 8 7 6
DFS Traversal : 4 3 1 7 2 6 5 8
4
/ \
3 5
/ \ \
2 1 8
| |
6 7
BFS Traversal : 4 3 5 1 2 8 7 6
| | |
| | |-------|
| | |
DFS Traversal : 4|3 1 7 2 6|5 8
(3, 1, 7, 2, 6)
属于以3为根的子树。由于1也是该子树的一部分,我们可以推断出3和5是4的唯一孩子。BFS Traversal : 4 3 5 1 2 8 7 6
| | |
| | |-|
| | |
DFS Traversal : 4 3 1 7 2 6 5 8
这样,我们可以展示出3和5是4的子节点。
只使用BFS和DFS的子集也可以完成此操作,这些子集包含属于同一子树的节点(例如在规则1演示中找到的子树):
使用规则1:
BFS Traversal: 1 2 7 6
| |
| |-|
| |
DFS Traversal: 1|7|2 6
这表明7是1的唯一子节点。
使用规则2:
BFS Traversal: 1 2 7 6
| |
| |-|
| |
DFS Traversal: 1 7 2 6
addchild(int parent, int child) := add the child to the specified parent node
void process(int[] bfs , int[] dfs)
int root = bfs[0]
//find all peers (nodes with the same level and parent in the tree) using Rule 2
int at = bfs.find(dfs[2])
int peers[at - 1]
for int i in [1 , at[
peers[i - 1] = bfs[i]
addchild(root , bfs[i])
//for each of the childtree of the tree find it's children using Rule 1
for int i in [0 , length(peers)[
//all nodes that are either peers[i] or a child of peers[i]
int[] children_dfs = dfs.subset(dfs.find(peers[i]) , (i < length(peers) - 1 ? dfs.find(peers[i + 1]) : length(dfs)) - 1)
//a subset of bfs containing peers[i] and it's children in the order they have in bfs
int[] children_bfs = bfs.allMatchingInOrder(children_dfs)
//generate the subtree
process(children_bfs , children_dfs)
[x , y[
表示范围从x
到不包括y
。allMatchingInOrder
函数应该生成一个数组,其中包含参数中所有值,并按照它们在被调用的数组中出现的顺序排列。例如:{0 , 1 , 2 , 3 , 4}.allMatchingInOrder({1 , 4 , 3})
将返回{1 , 3 , 4}
。subset()
函数应该生成一个子集,从第一个参数指定的索引开始,到第二个参数给定的索引结束(抱歉,这里实际上有一个错误)。 - user4668606[a,b)
表示范围,其中 a
包含在内,而 b
不包含在内。我认为这应该是标准符号,因为它被广泛使用。 - Mostafiz Rahman
3
的子节点被颠倒了。 - beaker