19
5
Inspired by a recent question on SO...
Write a function to print a binary tree in the following format:
3
/ \
1 5
\ / \
2 4 6
- The output should consist of a line of nodes, followed by a line of
/
and\
characters indicating relationships, followed by a line of nodes, etc. - You can assume all nodes are representable as a single character.
- Adjacent nodes on the lowest level should be separated by at least one space, nodes further up should be separated as appropriate.
- Nodes with two children should be placed precisely in the middle of their direct children.
- Relationship slashes should be halfway between the parent and the appropriate child (round whichever way you want).
Input:
The input will be provided as an argument to your function. I won't specify the exact structure of the tree, however it must be usable as an actual binary tree. No "trees are represented in my program as strings coincidentally looking like the expected output".
You may print to an output stream or return a string containing the output, your choice.
Points for shortest code, but I'd much prefer a fully working long solution than a 90%-working short one.
Update for the bounty:
For the bounty, I (Optimizer) am making slight changes:
- Input can be from STDIN,ARGV or function argument.
- Output needs to be on STDOUT (or
console.log
for JS) - You can assume that input is in a form of array, for ex.
[1,2,3]
or[1 2 3]
Update 2 - The binary tree should actually be a binary search tree. Since I did not mention this initially, I will allow users to treat the converting a normal array into a binary search tree array as a separate program and the final byte count will only be for the program to take in the array as argument and print it like a binary tree.
What do we do if the tree isn't complete (2^n-1 nodes for some n)? Some nodes (which ones?) have only one child. But if we're allowed to have nodes with only one child, the degenerate tree is easy to make (1-2-3-4-5-6 down and to the right, say). – Keith Randall – 2014-12-16T07:04:43.597
How you draw it for large numbers? For example
30000,1000,499999
– Mohsen – 2014-12-17T06:04:30.580Should we use several relationship slashes were appropriate? Must we use the minimum number of slashes? Should one distinguish between having a single left child and a single right child? Would it be fine to have leading spaces in every output line? – None – 2011-02-11T10:31:37.667