mad*_*MDT 4 algorithm graph breadth-first-search tree-traversal depth-first-search
我有一棵树的遍历BFS和DFS遍历.如何从这些遍历中重建树?
例如:
BFS Traversal : 4 3 5 1 2 8 7 6
DFS Traversal : 4 3 1 7 2 6 5 8
Run Code Online (Sandbox Code Playgroud)
然后树会像吼叫:
4
/ \
3 5
/ \ \
2 1 8
| |
6 7
Run Code Online (Sandbox Code Playgroud)
这只有在BFS和DFS使用完全相同的顺序来遍历子项时才有可能:
规则1:
BFS Traversal : 4 3 5 1 2 8 7 6
| | |
| | |-------|
| | |
DFS Traversal : 4|3 1 7 2 6|5 8
Run Code Online (Sandbox Code Playgroud)
正如这个例子所示,我们可以很容易地知道(3 , 1 , 7 , 2 , 6)属于一个以3为根的子树.由于1也是该子树的一部分,我们可以得出3和5是4的唯一子元素.
规则2:
BFS Traversal : 4 3 5 1 2 8 7 6
| | |
| | |-|
| | |
DFS Traversal : 4 3 1 7 2 6 5 8
Run Code Online (Sandbox Code Playgroud)
这样,我们可以证明3和5是4的孩子.
这也可以仅使用BFS和DFS的子集来保存属于同一子树的节点(此示例是在规则1的演示中找到的子树):
使用规则1:
BFS Traversal: 1 2 7 6
| |
| |-|
| |
DFS Traversal: 1|7|2 6
Run Code Online (Sandbox Code Playgroud)
这表明7是1的唯一孩子.
使用规则2:
BFS Traversal: 1 2 7 6
| |
| |-|
| |
DFS Traversal: 1 7 2 6
Run Code Online (Sandbox Code Playgroud)
因此,1和2是同一父母的孩子(将是3).
转换为伪代码,这将是这样的:
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)
Run Code Online (Sandbox Code Playgroud)