RosettaCodeData/Task/Visualize-a-tree/D/visualize-a-tree.d

21 lines
614 B
D
Raw Permalink Normal View History

2013-04-11 01:07:29 -07:00
import std.stdio, std.conv, std.algorithm, std.array;
2013-10-27 22:24:23 +00:00
struct Node(T) { T value; Node* left, right; }
2013-04-11 01:07:29 -07:00
2015-02-20 00:35:01 -05:00
string[] treeIndent(T)(in Node!T* t) pure nothrow @safe {
2013-10-27 22:24:23 +00:00
if (!t) return ["-- (null)"];
const tr = t.right.treeIndent;
return "--" ~ t.value.text ~
t.left.treeIndent.map!q{" |" ~ a}.array ~
(" `" ~ tr[0]) ~ tr[1 .. $].map!q{" " ~ a}.array;
2013-04-11 01:07:29 -07:00
}
void main () {
2013-10-27 22:24:23 +00:00
static N(T)(T v, Node!T* l=null, Node!T* r=null) {
return new Node!T(v, l, r);
2013-04-11 01:07:29 -07:00
}
const tree = N(1, N(2, N(4, N(7)), N(5)), N(3, N(6, N(8), N(9))));
2013-10-27 22:24:23 +00:00
writefln("%-(%s\n%)", tree.treeIndent);
2013-04-11 01:07:29 -07:00
}