Visualize a tree: Difference between revisions
m
syntax highlighting fixup automation
m (→{{header|Phix}}: made p2js and linux terminal compatible) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 22:
=={{header|11l}}==
{{trans|D}}
<
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"))</
=={{header|Ada}}==
Prints a tree of the current directory.
<
procedure Directory_Tree is
Line 77:
begin
Print_Tree(Ada.Directories.Current_Directory);
end Directory_Tree;</
{{out}}
Line 90:
=={{header|ALGOL 68}}==
<
# mode representing nodes of the tree #
Line 192:
animals /:= fish +:= reptiles +:= mammals;
print( ( TOHTML animals ) )</
{{out}}
<table border="1" cellspacing="4">
Line 275:
{{Trans|Python}}
{{Trans|JavaScript}}
<
-- box-drawing characters, with options for compacting
-- and pruning.
Line 845:
set my text item delimiters to dlm
str
end unlines</
{{Out}}
<pre>(NB – view in mono-spaced font)
Line 885:
=={{header|Batch File}}==
Displays a tree of the current directory.
<syntaxhighlight lang
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
This creates a native Windows Tree View control:
<
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%</
[[File:visualize_tree_bbc.gif]]
=={{header|C}}==
Print a simple tree to standard output:
<
#include <stdlib.h>
Line 993:
tree(n, 0);
return 0;
}</
{{out}}
<pre>
Line 1,015:
=={{header|C++}}==
<
#include <iostream>
#include <random>
Line 1,103:
return 0;
}</
{{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}}==
<
public static class VisualizeTree
Line 1,155:
}
}</
{{out}}
<pre>
Line 1,184:
=={{header|Clojure}}==
<
(draw-tree [[:A] [:B] [:C [:D [:E] [:F]] [:G]]])
</syntaxhighlight>
{{out}}
<pre>
Line 1,208:
=={{header|Common Lisp}}==
<
(labels
((rprint (list)
Line 1,239:
branches))
(terpri)))))))
(vis-h tree '("| "))))</
{{out}}
<
A
|
Line 1,272:
G
NIL</
or
<
(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>
{{out}}
<
(aa
(aaa
Line 1,319:
├─ ACB
└─ ACC
</syntaxhighlight>
=={{header|D}}==
{{trans|Haskell}}
<
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);
}</
{{out}}
<pre>--1
Line 1,367:
{{libheader| System.SysUtils}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
program Visualize_a_tree;
Line 1,447:
{$IFNDEF UNIX} readln; {$ENDIF}
end.</
{{out}}
<pre>┐root
Line 1,459:
=={{header|Elena}}==
ELENA 5.0 :
<
import extensions;
Line 1,522:
console.writeTree(tree).readChar()
}</
{{out}}
<pre>
Line 1,552:
=={{header|F_Sharp|F#}}==
<
| T of string * tree list
Line 1,582:
visualize example prefNone
|> Seq.iter (printfn "%s")</
{{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>.
<
CONSTANT: mammals { "mammals" { "deer" "gorilla" "dolphin" } }
CONSTANT: reptiles { "reptiles" { "turtle" "lizard" "snake" } }
{ "animals" ${ mammals reptiles } } dup . 10 margin set .</
{{out}}
<pre>
Line 1,632:
</pre>
An example showcasing tuples by displaying an AVL tree:
<
AVL{ { 1 2 } { 9 19 } { 3 4 } { 5 6 } } .</
{{out}}
<pre>
Line 1,680:
=={{header|FreeBASIC}}==
{{trans|Yabasic}}
<
Sub showTree(n As Integer, A As String)
Line 1,710:
Print !"\n\n\n"
showTree(0, "[1[2[3[4]]][5[6][7[8][9]]]]")
Sleep</
Line 1,716:
===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.
<
import (
Line 1,744:
}
fmt.Println(string(b))
}</
{{out}}
<pre>
Line 1,781:
===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.
<
import (
Line 1,811:
log.Fatal(err)
}
}</
{{out}}
<pre>
Line 1,839:
===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.
<
import "fmt"
Line 1,884:
}
f(0, "")
}</
{{out}}
<pre>
Line 1,898:
=={{header|Haskell}}==
Tree borrowed from [[Tree traversal]]:
<
deriving (Show, Eq)
Line 1,912:
ls = treeIndent$left t
main = mapM_ putStrLn $ treeIndent tree</
{{out}}
<pre>
Line 1,940:
We can ''fmap show'' over our tree of integers to derive a tree of strings, and apply `drawTree` to that.
<
tree :: Tree Int
Line 1,951:
main :: IO ()
main = (putStrLn . drawTree . fmap show) tree</
{{Out}}
<pre>1
Line 1,974:
The following works in both languages.
<
showTree("", " -", [1, [2,[3],[4,[5],[6]],[7,[11]]], [8,[9,[10]]] ])
write()
Line 1,987:
showTree(prefix, "`-", A[*A])
}
end</
Output:
Line 2,023:
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):
<
EW =: {: BOXC NB. east-west
Line 2,066:
extend=: 3 : '(+./\"1 (y=EW) *. *./\."1 y e.'' '',EW)}y,:EW'
</syntaxhighlight>
Example use:
<
┌─ 6
┌─ 1 ─── 3 ─┴─ 7
│ ┌─ 8
─ 0 ─┤ ┌─ 4 ─┴─ 9
└─ 2 ─┴─ 5 </
For comparison purposes, here's the node labels along with (in the following row) the index of their parent node:
<
0 1 2 3 4 5 6 7 8 9
_ 0 0 1 2 2 3 3 4 4</
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':
<
┌─ 6
┌─ 1 ─── 3 ────┴─ 7
│ ┌─ 8
─ george ─┤ ┌─ fred ─┴─ 9
└─ 2 ─┴─ 5 </
=={{header|Java}}==
Minimalist BST that can do nothing except print itself to stdout.
<
public static void main(String[] args) {
BinarySearchTree tree = new BinarySearchTree();
Line 2,172:
}
}
}</
<pre> 100
Line 2,187:
===HTML===
Javascript wrapped in HTML5 document. ''Should'' work in modern browsers.
<
<html id="doc">
<head><meta charset="utf-8"/>
Line 2,269:
<div id="tree"><a href="javascript:dom_tree('doc')">click me</a></div>
</body>
</html></
===Plain text===
====Vertically centered tree====
{{Trans|Python}} (Functional version)
<
'use strict';
Line 2,573:
// MAIN ---
return main();
})();</
{{Out}}
<pre>Compacted (parents not all vertically centered):
Line 2,609:
====Decorated outline====
<
'use strict';
Line 2,738:
// MAIN ---
return main();
})();</
{{Out}}
<pre>Alpha
Line 2,790:
</pre>
<
# Output: a stream of strings representing the tree
# In this implementation, empty arrays in the tree are simply ignored.
Line 2,816:
. as $tree
| "" | print($tree) ;</
'''Examples'''
<
["a",
["aa",
Line 2,838:
| ("Tree with array representation:\n\(.)\n",
printTree,
"")</
{{out}}
<pre>
Line 2,884:
=={{header|Julia}}==
Run from Julia REPL.
<
gx = kronecker(5, 12, 0.57, 0.19, 0.19)
gplot(gx)
</syntaxhighlight>
=={{header|Kotlin}}==
{{trans|C}}
<
import java.util.Random
Line 2,936:
val n = 8
tree(n, null)
}</
Sample output (unlike the C entry, should be different each time it's run):
Line 2,959:
=={{header|Lingo}}==
<
-- (minimal implementation with direct property access)
Line 2,983:
me.printTree(c, indent&" ")
end repeat
end</
Usage:
<
root = script("TreeItem").new("root")
a = script("TreeItem").new("a")
Line 3,001:
-- print the tree
root.printTree()</
{{Out}}
Line 3,016:
=={{header|Lua}}==
{{trans|C#}}
<
if type(ac) == "table" then
return {value=v,children=ac}
Line 3,079:
})
})
)</
{{out}}
<pre>A
Line 3,107:
=={{header|Maple}}==
<
GraphTheory:-DrawGraph(T, style = tree);</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Line 3,114:
Make a tree graph. In Mathematica, '''\[DirectedEdge]''' will appear as an arrow in the code.
<
3 \[DirectedEdge] 6, 4 \[DirectedEdge] 7};
t = TreeGraph[edges, GraphStyle -> "VintageDiagram"]</
[[File:Tree.jpg]]
Line 3,122:
Show the syntactical structure of the above code. '''Defer''' is added to impede '''TreeGraph''' from becoming a graphical object.
<
TreeGraph[{1 \[DirectedEdge] 2, 1 \[DirectedEdge] 3, 2 \[DirectedEdge] 4, 2 \[DirectedEdge] 5,
3 \[DirectedEdge] 6, 4 \[DirectedEdge] 7}, VertexLabels -> "Name"]]</
[[File:syntax.jpg]]
Line 3,132:
Here's another way to display a tree. The triangles open/close when clicked on.
<
OpenerView[{3, OpenerView[{TraditionalForm[Cos[x]], Plot[Cos[x], {x, 0, 10}, ImageSize -> 150]},
True]}, True]}}, True]</
[[File:opener.jpg]]
=={{header|Maxima}}==
<
g: random_tree(10)$
Line 3,146:
true
draw_graph(g)$</
=={{header|Nim}}==
{{trans|Haskell}}
<
type
Line 3,173:
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")</
{{out}}
Line 3,198:
=={{header|Perl}}==
<
use warnings;
use strict;
Line 3,248:
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);</
{{out}}
<pre> a
Line 3,275:
=={{header|Phix}}==
<!--<
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\VisualiseTree.exw
Line 3,333:
<span style="color: #000080;font-style:italic;">--pp(tree,{pp_Nest,10})</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span>
<!--</
{{out}}
<pre>
Line 3,353:
</pre>
A much simpler but less aesthetically pleasing way is just
<!--<
<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>
<!--</
{{out}}
<pre>
Line 3,375:
'view' is a built-in function in PicoLisp.
<
Output:
Line 3,409:
===XPCE===
XPCE is the SWI-Prolog native GUI library.
<
display_tree(Direction) :-
sformat(A, 'Display tree ~w', [Direction]),
Line 3,428:
send(D, display, T),
send(D, open).
</syntaxhighlight>
[[File:display_tree.png|900px]]
Line 3,436:
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:
<
[GCC 4.6.3] on linux2
Type "copyright", "credits" or "license()" for more information.
Line 3,483:
7,
8)
>>> </
pprint (and print), prints Pythons standard container types in a format that is valid python so Python could parse its output:
<
>>> pprint(tree, width=1)
('a',
Line 3,536:
>>> tree == copypasteoutput
True
>>> </
pprints width parameter allows it to fold some structure to better fit the page:
<
('a',
('b0',
Line 3,549:
'b1',
('C1', 'C2', ('D1', 'E', 'D2', 'D3'), 'C3')))
>>> </
pprint works with with a mix of nested container types. Here we create a tree from both lists and tuples:
<
... 'i3', 'jj', 'i4', ['kk', 'm'])), 'b1', ('C1', 'C2', ('D1', 'E',
... 'D2', 'D3'), 'C3'))]
Line 3,589:
'b1',
('C1', 'C2', ('D1', 'E', 'D2', 'D3'), 'C3'))]
>>> </
Line 3,597:
{{Works with|Python|3}}
<
from functools import reduce
Line 3,927:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>Fully compacted (parents not all centered):
Line 3,971:
====Simple decorated-outline tree====
{{Works with|Python|3}}
<
from itertools import (chain, repeat, starmap)
Line 4,061:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>1
Line 4,082:
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket/base
Line 4,096:
(visualize '(1 (2 (3 (4) (5) (6 (7))) (8 (9)) (10)) (11 (12) (13))))
</syntaxhighlight>
Output:
Line 4,130:
(formerly Perl 6)
<syntaxhighlight lang="raku"
:$indent = '',
:@mid = ('├─', '│ '),
Line 4,152:
my $tree = root=>[a=>[a1=>[a11=>[]]],b=>[b1=>[b11=>[]],b2=>[],b3=>[]]];
.map({.join("\n")}).join("\n").say for visualize-tree($tree, *.key, *.value.list);</
{{out}}
Line 4,166:
=={{header|REXX}}==
<
* 10.05.2014 Walter Pachl using the tree and the output format of C
**********************************************************************/
Line 4,237:
node.a.0level=node.father.0level+1
Return
</syntaxhighlight>
{{out}}
<pre>R
Line 4,257:
=={{header|Ruby}}==
Modifying [[Tree_traversal#Ruby]] by adding somewhere after the line
<syntaxhighlight lang="ruby">
root = BinaryTreeNode.from_array [1, [2, [4, 7], [5]], [3, [6, [8], [9]]]]
</syntaxhighlight>
the lines
<syntaxhighlight lang="ruby">
require 'pp'
pp root
</syntaxhighlight>
will produce:
{{out}}
Line 4,287:
@value=1>
</pre>
<syntaxhighlight lang="ruby">
def ptree(tree,indent=" ")
case tree
Line 4,300:
end
ptree [1,2,3,[4,5,6,[7,8,9]],3,[22,33]]
</syntaxhighlight>
will produce:
{{out}}
Line 4,320:
=={{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">
extern crate rustc_serialize;
extern crate term_painter;
Line 4,487:
println!("{}", tree);
}
</syntaxhighlight>
{{out}}
[[File:Visualize_a_tree-rust-1.png]]
Line 4,493:
=={{header|Sidef}}==
{{trans|Raku}}
<
indent = '',
mids = ['├─', '│ '],
Line 4,513:
var tree = 'root':['a':['a1':['a11':[]]],'b':['b1':['b11':[]],'b2':[],'b3':[]]]
say visualize_tree(tree, { .first }, { .second }).flatten.join("\n")</
{{out}}
<pre>
Line 4,529:
=={{header|Tcl}}==
{{tcllib|struct::tree}}
<
proc visualize_tree {tree {nameattr name}} {
Line 4,554:
}
}
}</
Demonstrating:
<
struct::tree t deserialize {root {} {} a 0 {} d 3 {} e 3 {} f 9 {} b 0 {} c 0 {}}
visualize_tree t</
{{out}}
<pre>
Line 4,573:
{{trans|C}}
{{libheader|Wren-dynamic}}
<
import "random" for Random
Line 4,611:
var n = 8
tree.call(n, null)</
{{out}}
Line 4,635:
=={{header|Yabasic}}==
<
dim colore$(1)
Line 4,667:
end switch
end sub
</syntaxhighlight>
=={{header|zkl}}==
Line 4,688:
It does this with data that looks like:
L("Network.TCPServerSocket","File","ZKLShell.Granny","Int","startup","Utils.Inspector","Thread.Straw","Ref","Utils.Argh" ...)
<
const INDENT=" ";
space:=""; lastPath:=L();
Line 4,708:
"" // so startup has something to display
}
</syntaxhighlight>
=={{header|PHP}}==
<syntaxhighlight lang="php">
<?php
Line 4,830:
?>
</syntaxhighlight>
{{out}}
|