Go - Find all nodes within range of one node in unknown tree like data structure

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

the other day I made a quick tool to figure out exactly what the question asked but with a fixed range, which works well just by using a stupid amount of for loops but I would like to make it work for a use definable range.

The data structure in looks like

<img src="https://i.stack.imgur.com/tfKKR.png" alt="this">

Where each node can link to any other number of nodes and can all link back to itself it you follow the right path(Which tended to break my implementations).

It s just defined as

type Node struct {

   Name string
   ID   int

}


And you can get a list of nodes it is linked with using a method which returns a slice of Nodes which gets the information from a database with around 5,000 entries.

Initially I tried some stuff with recursion which just ended up with me having a hurt head and code that just doesn t work. I just can t seem to get my head around this.

Thanks in advance, and if this type of data has a specific name I would love to know what it is!

Answers

My final code looked something like this

func rec(x Node, depth int) Node {
    s := make([]Node, 0)
    if depth == 0 {
        s = append(s, x)
    } else {
        for _, y := range x.Get() {
            s = append(s, rec(y, depth-1)...)
        }
    }
    return s
}

http://stackoverflow.com/users/2137314/siritinga http://stackoverflow.com/users/2137314/siritinga

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/26322823/find-all-nodes-within-range-of-one-node-in-unknown-tree-like-data-structure

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils