Visualize a tree: Difference between revisions

m
(Added Delphi example)
 
(11 intermediate revisions by 7 users not shown)
Line 22:
=={{header|11l}}==
{{trans|D}}
<langsyntaxhighlight lang="11l">T Node
String value
Node? left
Line 38:
 
V tree = Node(1, Node(2, Node(4, Node(7)), Node(5)), Node(3, Node(6, Node(8), Node(9))))
print(tree.tree_indent().join("\n"))</langsyntaxhighlight>
 
=={{header|Ada}}==
Prints a tree of the current directory.
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Ada.Directories;
 
procedure Directory_Tree is
Line 77:
begin
Print_Tree(Ada.Directories.Current_Directory);
end Directory_Tree;</langsyntaxhighlight>
 
{{out}}
Line 90:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68"># outputs nested html tables to visualise a tree #
 
# mode representing nodes of the tree #
Line 192:
animals /:= fish +:= reptiles +:= mammals;
 
print( ( TOHTML animals ) )</langsyntaxhighlight>
{{out}}
<table border="1" cellspacing="4">
Line 275:
{{Trans|Python}}
{{Trans|JavaScript}}
<langsyntaxhighlight AppleScriptlang="applescript">-- Vertically centered textual tree using UTF8 monospaced
-- box-drawing characters, with options for compacting
-- and pruning.
Line 845:
set my text item delimiters to dlm
str
end unlines</langsyntaxhighlight>
{{Out}}
<pre>(NB – view in mono-spaced font)
Line 885:
=={{header|Batch File}}==
Displays a tree of the current directory.
<syntaxhighlight lang ="batch file">@tree %cd%</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
This creates a native Windows Tree View control:
<langsyntaxhighlight lang="bbcbasic"> INSTALL @lib$+"WINLIB5"
ON ERROR SYS "MessageBox", @hwnd%, REPORT$, 0, 0 : QUIT
Line 944:
IF hnode% = 0 ERROR 100, "TVM_INSERTITEM failed"
SYS "InvalidateRect", hTree%, 0, 0
= hnode%</langsyntaxhighlight>
[[File:visualize_tree_bbc.gif]]
 
=={{header|C}}==
Print a simple tree to standard output:
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 993:
tree(n, 0);
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,015:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <functional>
#include <iostream>
#include <random>
Line 1,103:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>Node(Node(Node(Node(Node(-,4,-),17,Node(-,22,-)),28,-),30,Node(Node(-,36,-),48,Node(Node(Node(-,77,-),81,-),91,-))),100,Node(Node(Node(Node(-,117,-),125,Node(Node(-,131,-),151,Node(-,158,Node(-,163,-)))),176,Node(Node(-,192,-),193,-)),200,-))</pre>
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
 
public static class VisualizeTree
Line 1,155:
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,184:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(use 'vijual)
 
(draw-tree [[:A] [:B] [:C [:D [:E] [:F]] [:G]]])
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,208:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun visualize (tree)
(labels
((rprint (list)
Line 1,239:
branches))
(terpri)))))))
(vis-h tree '("| "))))</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="lisp">CL-USER> (visualize '(a b c ((d (e ((() ()))) f)) (g)))
A
|
Line 1,272:
G
NIL</langsyntaxhighlight>
or
<langsyntaxhighlight lang="lisp">(use-package :iterate)
(defun print-tree (tree value-function children-function)
(labels
Line 1,290:
(do-print-tree child (format nil "~a " prefix)))))))
(do-print-tree tree "")))
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="lisp">CL-USER>(print-tree '(a
(aa
(aaa
Line 1,319:
├─ ACB
└─ ACC
</syntaxhighlight>
</lang>
 
=={{header|D}}==
{{trans|Haskell}}
<langsyntaxhighlight lang="d">import std.stdio, std.conv, std.algorithm, std.array;
 
struct Node(T) { T value; Node* left, right; }
Line 1,342:
const tree = N(1, N(2, N(4, N(7)), N(5)), N(3, N(6, N(8), N(9))));
writefln("%-(%s\n%)", tree.treeIndent);
}</langsyntaxhighlight>
{{out}}
<pre>--1
Line 1,367:
{{libheader| System.SysUtils}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Visualize_a_tree;
 
Line 1,447:
 
{$IFNDEF UNIX} readln; {$ENDIF}
end.</langsyntaxhighlight>
{{out}}
<pre>┐root
Line 1,459:
=={{header|Elena}}==
ELENA 5.0 :
<langsyntaxhighlight lang="elena">import system'routines;
import extensions;
 
Line 1,522:
console.writeTree(tree).readChar()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,552:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">type tree =
| T of string * tree list
 
Line 1,582:
 
visualize example prefNone
|> Seq.iter (printfn "%s")</langsyntaxhighlight>
{{out}}
<pre>root
Line 1,594:
=={{header|Factor}}==
Factor's prettyprinter does this by default with any nested sequences and/or tuples. There are dynamic variables that can be altered to change the prettyprinter's default behavior. The most interesting are <code>tab-size</code> and <code>margin</code> for customizing the look of a tree. For smaller trees, it's best to change <code>margin</code> from its default of <code>64</code> to something low, perhaps <code>10</code>.
<langsyntaxhighlight lang="factor">USE: literals
 
CONSTANT: mammals { "mammals" { "deer" "gorilla" "dolphin" } }
CONSTANT: reptiles { "reptiles" { "turtle" "lizard" "snake" } }
 
{ "animals" ${ mammals reptiles } } dup . 10 margin set .</langsyntaxhighlight>
{{out}}
<pre>
Line 1,632:
</pre>
An example showcasing tuples by displaying an AVL tree:
<langsyntaxhighlight lang="factor">USE: trees.avl
AVL{ { 1 2 } { 9 19 } { 3 4 } { 5 6 } } .</langsyntaxhighlight>
{{out}}
<pre>
Line 1,671:
=={{header|Fōrmulæ}}==
 
In [http{{FormulaeEntry|page=https://wiki.formulae.org/?script=examples/Visualize_a_tree this] page you can see the solution of this task.}}
 
'''Solution'''
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text ([http://wiki.formulae.org/Editing_F%C5%8Drmul%C3%A6_expressions more info]). Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for transportation effects more than visualization and edition.
 
Fōrmulæ is a homoiconic language using expression trees as its fundamental structure, so managing trees is very natural.
 
'''Creating trees from expressions'''
 
The ToTree expression creates a tree from a given expression. see the following examples:
 
[[File:Fōrmulæ - Visualize a tree 01.png]]
 
[[File:Fōrmulæ - Visualize a tree 02.png]]
 
Be aware the the expression will be first reduced, like the following:
 
[[File:Fōrmulæ - Visualize a tree 03.png]]
 
[[File:Fōrmulæ - Visualize a tree 04.png]]
 
It order to avoid the reduction, the use of the Protect expression is recommended:
 
[[File:Fōrmulæ - Visualize a tree 05.png]]
 
[[File:Fōrmulæ - Visualize a tree 06.png]]
 
In the following example, it is shown that a matrix is a list containing (same cardinality) sublists:
 
[[File:Fōrmulæ - Visualize a tree 07.png]]
 
[[File:Fōrmulæ - Visualize a tree 08.png]]
 
'''Creating trees programatically'''
 
The tree, like any other expression in Fōrmulæ is a first-class citizen of the language. Fōrmulæ also supports high-order functions, so trees can be set as parameters of functions, or retrieved from functions.
 
The following example shows a function that produces a Fibonacci tree, a tree that shows the calls of a function that recursively calculates Fibonacci numbers:
 
[[File:Fōrmulæ - Fibonacci sequence 03.png]]
 
[[File:Fōrmulæ - Fibonacci sequence 04.png]]
 
[[File:Fōrmulæ - Fibonacci sequence 05.png]]
 
=={{header|FreeBASIC}}==
{{trans|Yabasic}}
<syntaxhighlight lang="freebasic">Dim Shared As Ubyte colores(4) => {7,13,14,3,2}
 
Sub showTree(n As Integer, A As String)
Dim As Integer i, co = 0, b = 1, col
Dim As String cs = Left(A, 1)
If cs = "" Then Exit Sub
Select Case cs
Case "["
co += 1 : showTree(n + 1, Right(A, Len(A) - 1))
Exit Select
Case "]"
co -= 1 : showTree(n - 1, Right(A, Len(A) - 1))
Exit Select
Case Else
For i = 2 To n
Print " ";
co = n
Next i
Color colores(co) : Print !"\&hc0-"; cs
showTree(n, Right(A, Len(A) - 1))
Exit Select
End Select
End Sub
 
Cls
showTree(0, "[1[2[3][4[5][6]][7]][8[9]]]")
Print !"\n\n\n"
showTree(0, "[1[2[3[4]]][5[6][7[8][9]]]]")
Sleep</syntaxhighlight>
 
The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code.
 
=={{header|Go}}==
===JSON===
Not the most economical output, but at least json.MarshalIndent is in the Go standard library. Note that the definition of Node has nothing JSON specific about it; it's an ordinary struct.
<langsyntaxhighlight Golang="go">package main
 
import (
Line 1,708 ⟶ 1,781:
}
fmt.Println(string(b))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,745 ⟶ 1,818:
===TOML===
It works in this case, but TOML wasn't really designed for this and encoders may have trouble with general trees. Empty trees and nils for example might be problematic depending on your data structures and limitations of your TOML encoder. YMMV.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,775 ⟶ 1,848:
log.Fatal(err)
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,803 ⟶ 1,876:
===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.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,848 ⟶ 1,921:
}
f(0, "")
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,862 ⟶ 1,935:
=={{header|Haskell}}==
Tree borrowed from [[Tree traversal]]:
<langsyntaxhighlight lang="haskell">data Tree a = Empty | Node { value :: a, left :: Tree a, right :: Tree a }
deriving (Show, Eq)
 
Line 1,876 ⟶ 1,949:
ls = treeIndent$left t
 
main = mapM_ putStrLn $ treeIndent tree</langsyntaxhighlight>
{{out}}
<pre>
Line 1,904 ⟶ 1,977:
We can ''fmap show'' over our tree of integers to derive a tree of strings, and apply `drawTree` to that.
 
<langsyntaxhighlight lang="haskell">import Data.Tree (Tree(..), drawTree)
 
tree :: Tree Int
Line 1,915 ⟶ 1,988:
 
main :: IO ()
main = (putStrLn . drawTree . fmap show) tree</langsyntaxhighlight>
{{Out}}
<pre>1
Line 1,938 ⟶ 2,011:
 
The following works in both languages.
<langsyntaxhighlight lang="unicon">procedure main(A)
showTree("", " -", [1, [2,[3],[4,[5],[6]],[7,[11]]], [8,[9,[10]]] ])
write()
Line 1,951 ⟶ 2,024:
showTree(prefix, "`-", A[*A])
}
end</langsyntaxhighlight>
 
Output:
Line 1,987 ⟶ 2,060:
Or, adapted to the [[Tree_traversal#J:_Alternate_implementation|parent index]] representation of a tree (which allows different nodes to share labels and may also be more convenient for other reasons):
 
<langsyntaxhighlight Jlang="j">BOXC=: 9!:6 '' NB. box drawing characters
EW =: {: BOXC NB. east-west
 
Line 2,030 ⟶ 2,103:
 
extend=: 3 : '(+./\"1 (y=EW) *. *./\."1 y e.'' '',EW)}y,:EW'
</syntaxhighlight>
</lang>
 
Example use:
 
<langsyntaxhighlight lang="j"> (i.10) showtree _,}.p:inv i.10
┌─ 6
┌─ 1 ─── 3 ─┴─ 7
│ ┌─ 8
─ 0 ─┤ ┌─ 4 ─┴─ 9
└─ 2 ─┴─ 5 </langsyntaxhighlight>
 
For comparison purposes, here's the node labels along with (in the following row) the index of their parent node:
 
<langsyntaxhighlight lang="j"> (i.10),: _,}.p:inv i.10
0 1 2 3 4 5 6 7 8 9
_ 0 0 1 2 2 3 3 4 4</langsyntaxhighlight>
 
Also, note that labels can be arbitrary. Here, we used numeric labels because they were concise and convenient. But, for example, we can replace the label '0' with 'george' and the label '4' with 'fred':
 
<langsyntaxhighlight lang="j"> ((<'george') 0} (<'fred') 4} ":each i.10)showtree _,}.p:inv i.10
┌─ 6
┌─ 1 ─── 3 ────┴─ 7
│ ┌─ 8
─ george ─┤ ┌─ fred ─┴─ 9
└─ 2 ─┴─ 5 </langsyntaxhighlight>
 
=={{header|Java}}==
Minimalist BST that can do nothing except print itself to stdout.
<langsyntaxhighlight lang="java">public class VisualizeTree {
public static void main(String[] args) {
BinarySearchTree tree = new BinarySearchTree();
Line 2,136 ⟶ 2,209:
}
}
}</langsyntaxhighlight>
 
<pre> 100
Line 2,151 ⟶ 2,224:
===HTML===
Javascript wrapped in HTML5 document. ''Should'' work in modern browsers.
<langsyntaxhighlight lang="html"><!doctype html>
<html id="doc">
<head><meta charset="utf-8"/>
Line 2,233 ⟶ 2,306:
<div id="tree"><a href="javascript:dom_tree('doc')">click me</a></div>
</body>
</html></langsyntaxhighlight>
 
===Plain text===
====Vertically centered tree====
{{Trans|Python}} (Functional version)
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 2,537 ⟶ 2,610:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>Compacted (parents not all vertically centered):
Line 2,573 ⟶ 2,646:
 
====Decorated outline====
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 2,702 ⟶ 2,775:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>Alpha
Line 2,737 ⟶ 2,810:
└─ Lambda</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
In this entry, a tree $t is represented by an array [root, child1,
child2 ...] where root must be present and cannot be an array, and
the children, which may also be trees, may all be absent.
 
The tree [0, 1, 2, 3] is displayed as:
<pre>
0
├─ 1
├─ 2
└─ 3
</pre>
 
<syntaxhighlight lang="jq"># Input: an array representing a tree
# Output: a stream of strings representing the tree
# In this implementation, empty arrays in the tree are simply ignored.
def printTree:
 
def tidy:
sub("└─$"; " ")
| sub("├─$"; "| ") ;
 
# Input: a string prefix
def print($tree):
if $tree|type != "array" then . + ($tree|tostring)
else # ignore empty arrays
($tree | map(select(if type == "array" then length>0 else true end))) as $tree
| if $tree|length == 0 then empty
elif $tree|length == 1
then print($tree[0])
else print($tree[0]),
($tree[1:] as $children
| tidy as $p
| ($p + ( "├─" | print($children[:-1][]))),
($p + ( "└─" | print($children[-1]))) )
end
end ;
 
. as $tree
| "" | print($tree) ;</syntaxhighlight>
'''Examples'''
<syntaxhighlight lang="jq">def bigTree:
["a",
["aa",
["aaa",
["aaaa"],
["aaab",
["aaaba"],
["aaabb"]],
["aaac"]]],
["ab"],
["ac",
["aca"],
["acb"],
["acc"]]] ;
 
[0, 1, 2, 3],
[1,[2,3,[4, 5, [6,7,8], 9, [10,11]]]],
bigTree
| ("Tree with array representation:\n\(.)\n",
printTree,
"")</syntaxhighlight>
{{out}}
<pre>
Tree with array representation:
[0,1,2,3]
 
0
├─1
├─2
└─3
 
Tree with array representation:
[1,[2,3,[4,5,[6,7,8],9,[10,11]]]]
 
1
└─2
├─3
└─4
├─5
├─6
| ├─7
| └─8
├─9
└─10
└─11
 
Tree with array representation:
["a",["aa",["aaa",["aaaa"],["aaab",["aaaba"],["aaabb"]],["aaac"]]],["ab"],["ac",["aca"],["acb"],["acc"]]]
 
a
├─aa
| └─aaa
| ├─aaaa
| ├─aaab
| | ├─aaaba
| | └─aaabb
| └─aaac
├─ab
└─ac
├─aca
├─acb
└─acc
</pre>
 
=={{header|Julia}}==
Run from Julia REPL.
<langsyntaxhighlight Julialang="julia">using Gadfly, LightGraphs, GraphPlot
 
gx = kronecker(5, 12, 0.57, 0.19, 0.19)
gplot(gx)
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
{{trans|C}}
<langsyntaxhighlight lang="scala">// version 1.2.0
 
import java.util.Random
Line 2,792 ⟶ 2,973:
val n = 8
tree(n, null)
}</langsyntaxhighlight>
 
Sample output (unlike the C entry, should be different each time it's run):
Line 2,815 ⟶ 2,996:
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">-- parent script "TreeItem"
-- (minimal implementation with direct property access)
 
Line 2,839 ⟶ 3,020:
me.printTree(c, indent&" ")
end repeat
end</langsyntaxhighlight>
Usage:
<langsyntaxhighlight lang="lingo">-- create a tree
root = script("TreeItem").new("root")
a = script("TreeItem").new("a")
Line 2,857 ⟶ 3,038:
 
-- print the tree
root.printTree()</langsyntaxhighlight>
 
{{Out}}
Line 2,872 ⟶ 3,053:
=={{header|Lua}}==
{{trans|C#}}
<langsyntaxhighlight lang="lua">function makeTree(v,ac)
if type(ac) == "table" then
return {value=v,children=ac}
Line 2,935 ⟶ 3,116:
})
})
)</langsyntaxhighlight>
{{out}}
<pre>A
Line 2,963 ⟶ 3,144:
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">T := GraphTheory:-Graph([1, 2, 3, 4, 5], {{1, 2}, {2, 3}, {2, 4}, {4, 5}}):
GraphTheory:-DrawGraph(T, style = tree);</langsyntaxhighlight>
 
=={{header|Mathematica}}==
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
=== Tree graph ===
Make a tree graph. In Mathematica, '''\[DirectedEdge]''' will appear as an arrow in the code.
 
<langsyntaxhighlight Mathematicalang="mathematica">edges = {1 \[DirectedEdge] 2, 1 \[DirectedEdge] 3, 2 \[DirectedEdge] 4, 2 \[DirectedEdge] 5,
3 \[DirectedEdge] 6, 4 \[DirectedEdge] 7};
t = TreeGraph[edges, GraphStyle -> "VintageDiagram"]</langsyntaxhighlight>
 
[[File:Tree.jpg]]
Line 2,979 ⟶ 3,159:
Show the syntactical structure of the above code. '''Defer''' is added to impede '''TreeGraph''' from becoming a graphical object.
 
<langsyntaxhighlight Mathematicalang="mathematica">TreeForm[Defer@
TreeGraph[{1 \[DirectedEdge] 2, 1 \[DirectedEdge] 3, 2 \[DirectedEdge] 4, 2 \[DirectedEdge] 5,
3 \[DirectedEdge] 6, 4 \[DirectedEdge] 7}, VertexLabels -> "Name"]]</langsyntaxhighlight>
 
[[File:syntax.jpg]]
Line 2,989 ⟶ 3,169:
Here's another way to display a tree. The triangles open/close when clicked on.
 
<langsyntaxhighlight Mathematicalang="mathematica">OpenerView[{1, Column@{OpenerView[{2, Column@{OpenerView[{4, 7}, True], 5}}, True],
OpenerView[{3, OpenerView[{TraditionalForm[Cos[x]], Plot[Cos[x], {x, 0, 10}, ImageSize -> 150]},
True]}, True]}}, True]</langsyntaxhighlight>
 
[[File:opener.jpg]]
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">load(graphs)$
 
g: random_tree(10)$
Line 3,003 ⟶ 3,183:
true
 
draw_graph(g)$</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|Haskell}}
<langsyntaxhighlight lang="nim">import strutils
 
type
Line 3,030 ⟶ 3,210:
let tree = 1.n(2.n(4.n(7.n),5.n),3.n(6.n(8.n,9.n)))
 
echo tree.indent.join("\n")</langsyntaxhighlight>
 
{{out}}
Line 3,055 ⟶ 3,235:
=={{header|Perl}}==
 
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
use warnings;
use strict;
Line 3,105 ⟶ 3,285:
my $tree = 'a(b0(c1,c2(d(ef,gh)),c3(i1,i2,i3(jj),i4(kk,m))),b1(C1,C2(D1(E),D2,D3),C3))';
my $parsed = [parse($tree)];
output($parsed);</langsyntaxhighlight>
{{out}}
<pre> a
Line 3,132 ⟶ 3,312:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
<span style="color: #008080;">function</span> <span style="color: #000000;">rand_tree</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">low</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">high</span><span style="color: #0000FF;">)</span>
-- demo\rosetta\VisualiseTree.exw
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">2</span> <span style="color: #008080;">do</span>
--</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">v</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #000000;">high</span><span style="color: #0000FF;">-</span><span style="color: #000000;">low</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">+</span><span style="color: #000000;">low</span>
<span style="color: #008080;">ifwith</span> <span style="color: #000000;">v</span><span style="color: #0000FF;">!=</span><span style="color: #000000008080;">lowjavascript_semantics</span>
<span style="color: #008080;">and</span> <span style="color: #000000;">v</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">high</span> <span style="color: #008080;">then</span>
<span style="color: #000080;font-style:italic;">-- To the theme tune of the Milk Tray Ad iyrt,
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">v</span><span style="color: #0000FF;">,</span><span style="color: #000000;">rand_tree</span><span style="color: #0000FF;">(</span><span style="color: #000000;">low</span><span style="color: #0000FF;">,</span><span style="color: #000000;">v</span><span style="color: #0000FF;">),</span><span style="color: #000000;">rand_tree</span><span style="color: #0000FF;">(</span><span style="color: #000000;">v</span><span style="color: #0000FF;">,</span><span style="color: #000000;">high</span><span style="color: #0000FF;">)}</span>
-- All because the Windows console hates utf8:</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">TL</span> <span style="color: #0080800000FF;">end=</span> '\<span style="color: #008080000000;">for#DA</span>'<span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- aka '┌'</span>
<span style="color: #008080000000;">returnVT</span> <span style="color: #0000FF;">=</span> '\<span style="color: #000000;">0#B3</span>'<span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- aka '│'</span>
<span style="color: #000000;">BL</span> <span style="color: #0000FF;">=</span> '\<span style="color: #000000;">#C0</span>'<span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- aka '└'</span>
<span style="color: #000000;">HZ</span> <span style="color: #0000FF;">=</span> '\<span style="color: #000000;">#C4</span>'<span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- aka '─'</span>
<span style="color: #000000;">HS</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"\#C4"</span> <span style="color: #000080;font-style:italic;">-- (string version of HZ)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">w1252_to_utf8</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">WINDOWS</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">substitute_all</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,{</span> <span style="color: #000000;">TL</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">VT</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">BL</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">HZ</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #008000;">"┌"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"│"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"└"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"─"</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #000080;font-style:italic;">--&lt;/hates utf8&gt;</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">tree</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">rand_tree</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">20</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (can be 0, ~1% chance)</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">visualise_tree</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">tree</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">string</span> <span style="color: #000000;">root</span><span style="color: #0000FF;">=</span><span style="color: #000000;">HS</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">Horizontal</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">#C4</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">Horizontals</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"\#C4"</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">TopLeft</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">#DA</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">Vertical</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">#B3</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">BtmLeft</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">#C0</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">visualise_tree</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">tree</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">string</span> <span style="color: #000000;">root</span><span style="color: #0000FF;">=</span><span style="color: #000000;">Horizontals</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #004080;">atom</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tree</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"&lt;empty&gt;\n"</span><span style="color: #0000FF;">)</span>
Line 3,159 ⟶ 3,342:
<span style="color: #004080;">integer</span> <span style="color: #000000;">g</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">root</span><span style="color: #0000FF;">[$]</span>
<span style="color: #008080;">if</span> <span style="color: #004080;">sequence</span><span style="color: #0000FF;">(</span><span style="color: #000000;">l</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">root</span><span style="color: #0000FF;">[$]</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">g</span><span style="color: #0000FF;">=</span><span style="color: #000000;">TopLeftTL</span> <span style="color: #008080;">or</span> <span style="color: #000000;">g</span><span style="color: #0000FF;">=</span><span style="color: #000000;">HorizontalHZ</span><span style="color: #0000FF;">?</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">:</span><span style="color: #000000;">VerticalVT</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">visualise_tree</span><span style="color: #0000FF;">(</span><span style="color: #000000;">l</span><span style="color: #0000FF;">,</span><span style="color: #000000;">root</span><span style="color: #0000FF;">&</span><span style="color: #000000;">TopLeftTL</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">root</span><span style="color: #0000FF;">[$]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">g</span>
<span style="color: #7060A8;">putsprintf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s%d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">w1252_to_utf8</span><span style="color: #0000FF;">(</span><span style="color: #000000;">root</span><span style="color: #0000FF;">),</span><span style="color: #000000;">v</span><span style="color: #0000FF;">})</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">v</span>
<span style="color: #008080;">if</span> <span style="color: #004080;">sequence</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">root</span><span style="color: #0000FF;">[$]</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">g</span><span style="color: #0000FF;">=</span><span style="color: #000000;">TopLeftTL</span><span style="color: #0000FF;">?</span><span style="color: #000000;">VerticalVT</span><span style="color: #0000FF;">:</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">visualise_tree</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">,</span><span style="color: #000000;">root</span><span style="color: #0000FF;">&</span><span style="color: #000000;">BtmLeftBL</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">rand_tree</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">low</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">high</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">2</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">v</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #000000;">high</span><span style="color: #0000FF;">-</span><span style="color: #000000;">low</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">+</span><span style="color: #000000;">low</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">v</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">low</span>
<span style="color: #008080;">and</span> <span style="color: #000000;">v</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">high</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">v</span><span style="color: #0000FF;">,</span><span style="color: #000000;">rand_tree</span><span style="color: #0000FF;">(</span><span style="color: #000000;">low</span><span style="color: #0000FF;">,</span><span style="color: #000000;">v</span><span style="color: #0000FF;">),</span><span style="color: #000000;">rand_tree</span><span style="color: #0000FF;">(</span><span style="color: #000000;">v</span><span style="color: #0000FF;">,</span><span style="color: #000000;">high</span><span style="color: #0000FF;">)}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">tree</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">rand_tree</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">20</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (can be 0, &lt;1% chance)</span>
<span style="color: #000000;">visualise_tree</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tree</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">--pp(tree,{pp_Nest,10})</span>
<!--</lang>-->
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 3,193 ⟶ 3,390:
</pre>
A much simpler but less aesthetically pleasing way is just
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tree</span><span style="color: #0000FF;">,{</span><span style="color: #004600;">pp_Nest</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">})</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,215 ⟶ 3,412:
'view' is a built-in function in PicoLisp.
 
<langsyntaxhighlight PicoLisplang="picolisp">(view '(1 (2 (3 (4) (5) (6 (7))) (8 (9)) (10)) (11 (12) (13))))</langsyntaxhighlight>
 
Output:
Line 3,249 ⟶ 3,446:
===XPCE===
XPCE is the SWI-Prolog native GUI library.
<langsyntaxhighlight lang="prolog">% direction may be horizontal/vertical/list
display_tree(Direction) :-
sformat(A, 'Display tree ~w', [Direction]),
Line 3,268 ⟶ 3,465:
send(D, display, T),
send(D, open).
</syntaxhighlight>
</lang>
[[File:display_tree.png|900px]]
 
Line 3,276 ⟶ 3,473:
 
If you set the presumed width of the output to 1 then pprint will print each level of a nested tuple (which is Pythons obvious method of creating a tree), on a separate line:
<langsyntaxhighlight lang="python">Python 3.2.3 (default, May 3 2012, 15:54:42)
[GCC 4.6.3] on linux2
Type "copyright", "credits" or "license()" for more information.
Line 3,323 ⟶ 3,520:
7,
8)
>>> </langsyntaxhighlight>
 
pprint (and print), prints Pythons standard container types in a format that is valid python so Python could parse its output:
<langsyntaxhighlight lang="python">>>> tree = "a",("b0",("c1","c2",("d",("ef","gh")),"c3",("i1","i2","i3",("jj"),"i4",("kk","m"))),"b1",("C1","C2",("D1",("E"),"D2","D3"),"C3"))
>>> pprint(tree, width=1)
('a',
Line 3,376 ⟶ 3,573:
>>> tree == copypasteoutput
True
>>> </langsyntaxhighlight>
 
pprints width parameter allows it to fold some structure to better fit the page:
<langsyntaxhighlight lang="python">>>> pprint(tree, width=60)
('a',
('b0',
Line 3,389 ⟶ 3,586:
'b1',
('C1', 'C2', ('D1', 'E', 'D2', 'D3'), 'C3')))
>>> </langsyntaxhighlight>
 
pprint works with with a mix of nested container types. Here we create a tree from both lists and tuples:
<langsyntaxhighlight lang="python">>>> mixedtree = ['a', ('b0', ('c1', 'c2', ['d', ('ef', 'gh')], 'c3', ('i1', 'i2',
... 'i3', 'jj', 'i4', ['kk', 'm'])), 'b1', ('C1', 'C2', ('D1', 'E',
... 'D2', 'D3'), 'C3'))]
Line 3,429 ⟶ 3,626:
'b1',
('C1', 'C2', ('D1', 'E', 'D2', 'D3'), 'C3'))]
>>> </langsyntaxhighlight>
 
 
Line 3,437 ⟶ 3,634:
 
{{Works with|Python|3}}
<langsyntaxhighlight lang="python">'''Textually visualized tree, with vertically-centered parent nodes'''
 
from functools import reduce
Line 3,767 ⟶ 3,964:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Fully compacted (parents not all centered):
Line 3,811 ⟶ 4,008:
====Simple decorated-outline tree====
{{Works with|Python|3}}
<langsyntaxhighlight lang="python">'''Visualize a tree'''
 
from itertools import (chain, repeat, starmap)
Line 3,901 ⟶ 4,098:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>1
Line 3,922 ⟶ 4,119:
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket/base
 
Line 3,936 ⟶ 4,133:
 
(visualize '(1 (2 (3 (4) (5) (6 (7))) (8 (9)) (10)) (11 (12) (13))))
</syntaxhighlight>
</lang>
 
Output:
Line 3,970 ⟶ 4,167:
(formerly Perl 6)
 
<syntaxhighlight lang="raku" perl6line>sub visualize-tree($tree, &label, &children,
:$indent = '',
:@mid = ('├─', '│ '),
Line 3,992 ⟶ 4,189:
my $tree = root=>[a=>[a1=>[a11=>[]]],b=>[b1=>[b11=>[]],b2=>[],b3=>[]]];
 
.map({.join("\n")}).join("\n").say for visualize-tree($tree, *.key, *.value.list);</langsyntaxhighlight>
 
{{out}}
Line 4,006 ⟶ 4,203:
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* 10.05.2014 Walter Pachl using the tree and the output format of C
**********************************************************************/
Line 4,077 ⟶ 4,274:
node.a.0level=node.father.0level+1
Return
</syntaxhighlight>
</lang>
{{out}}
<pre>R
Line 4,097 ⟶ 4,294:
=={{header|Ruby}}==
Modifying [[Tree_traversal#Ruby]] by adding somewhere after the line
<syntaxhighlight lang="ruby">
<lang Ruby>
root = BinaryTreeNode.from_array [1, [2, [4, 7], [5]], [3, [6, [8], [9]]]]
</syntaxhighlight>
</lang>
the lines
<syntaxhighlight lang="ruby">
<lang Ruby>
require 'pp'
pp root
</syntaxhighlight>
</lang>
will produce:
{{out}}
Line 4,127 ⟶ 4,324:
@value=1>
</pre>
<syntaxhighlight lang="ruby">
<lang Ruby>
def ptree(tree,indent=" ")
case tree
Line 4,140 ⟶ 4,337:
end
ptree [1,2,3,[4,5,6,[7,8,9]],3,[22,33]]
</syntaxhighlight>
</lang>
will produce:
{{out}}
Line 4,160 ⟶ 4,357:
=={{header|Rust}}==
Console visualization of binary trees translated from parts of [http://rosettacode.org/wiki/AVL_tree/C the C AVL tree solution].
<syntaxhighlight lang="rust">
<lang Rust>
extern crate rustc_serialize;
extern crate term_painter;
Line 4,327 ⟶ 4,524:
println!("{}", tree);
}
</syntaxhighlight>
</lang>
{{out}}
[[File:Visualize_a_tree-rust-1.png]]
Line 4,333 ⟶ 4,530:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func visualize_tree(tree, label, children,
indent = '',
mids = ['├─', '│ '],
Line 4,353 ⟶ 4,550:
 
var tree = 'root':['a':['a1':['a11':[]]],'b':['b1':['b11':[]],'b2':[],'b3':[]]]
say visualize_tree(tree, { .first }, { .second }).flatten.join("\n")</langsyntaxhighlight>
{{out}}
<pre>
Line 4,369 ⟶ 4,566:
=={{header|Tcl}}==
{{tcllib|struct::tree}}
<langsyntaxhighlight lang="tcl">package require struct::tree
 
proc visualize_tree {tree {nameattr name}} {
Line 4,394 ⟶ 4,591:
}
}
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl"># Sample tree to demonstrate with
struct::tree t deserialize {root {} {} a 0 {} d 3 {} e 3 {} f 9 {} b 0 {} c 0 {}}
visualize_tree t</langsyntaxhighlight>
{{out}}
<pre>
Line 4,413 ⟶ 4,610:
{{trans|C}}
{{libheader|Wren-dynamic}}
<langsyntaxhighlight ecmascriptlang="wren">import "./dynamic" for Struct
import "random" for Random
 
Line 4,451 ⟶ 4,648:
 
var n = 8
tree.call(n, null)</langsyntaxhighlight>
 
{{out}}
Line 4,475 ⟶ 4,672:
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">clear screen
 
dim colore$(1)
Line 4,507 ⟶ 4,704:
end switch
end sub
</syntaxhighlight>
</lang>
 
=={{header|zkl}}==
Line 4,528 ⟶ 4,725:
It does this with data that looks like:
L("Network.TCPServerSocket","File","ZKLShell.Granny","Int","startup","Utils.Inspector","Thread.Straw","Ref","Utils.Argh" ...)
<langsyntaxhighlight lang="zkl">fcn vaultDir(out=Console){
const INDENT=" ";
space:=""; lastPath:=L();
Line 4,548 ⟶ 4,745:
"" // so startup has something to display
}
</syntaxhighlight>
</lang>
 
=={{header|PHP}}==
<syntaxhighlight lang="php">
<lang PHP>
<?php
 
Line 4,670 ⟶ 4,867:
 
?>
</syntaxhighlight>
</lang>
 
{{out}}
2,120

edits