簡體   English   中英

如何使用它的BFS和DFS遍歷來構造樹

[英]How to construct a tree with it's BFS and DFS traversal

我有一個樹的BFSDFS遍歷。 如何從這些遍歷中重建樹?

例如:

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使用完全相同的順序來遍歷子項時,才可以執行此操作:

規則1:

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,7,2,6 (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

這樣,我們可以證明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

因此,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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM