Jump to content

Visualize a tree: Difference between revisions

→‎{{header|Go}}: Yet another solution, this one more like others on the page.
(Nimrod -> Nim)
(→‎{{header|Go}}: Yet another solution, this one more like others on the page.)
Line 405:
[[Children]]
Name = "c"
</pre>
===Unicode===
A non-library solution, more like a number of other solutions on this page, and with more compact output. The tree representation here uses integer indexes rather than pointers, which is efficient for representation and computation. A serialization format like JSON or TOML wouldn't see it as a hierarchical structure, but the code here knows to interpret the child ints as node indexes.
<lang go>package main
 
import "fmt"
 
type tree []node
 
type node struct {
label string
children []int // indexes into tree
}
 
func main() {
vis(tree{
0: node{"root", []int{1, 2, 3}},
1: node{"ei", []int{4, 5}},
2: node{"bee", nil},
3: node{"si", nil},
4: node{"dee", nil},
5: node{"y", []int{6}},
6: node{"eff", nil},
})
}
 
func vis(t tree) {
if len(t) == 0 {
fmt.Println("<empty>")
return
}
var f func(int, string)
f = func(n int, pre string) {
ch := t[n].children
if len(ch) == 0 {
fmt.Println("╴", t[n].label)
return
}
fmt.Println("┐", t[n].label)
last := len(ch) - 1
for _, ch := range ch[:last] {
fmt.Print(pre, "├─")
f(ch, pre+"│ ")
}
fmt.Print(pre, "└─")
f(ch[last], pre+" ")
}
f(0, "")
}</lang>
{{out}}
<pre>
┐ root
├─┐ ei
│ ├─╴ dee
│ └─┐ y
│ └─╴ eff
├─╴ bee
└─╴ si
</pre>
 
1,707

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.