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
\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).
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
- You can assume that input is in a form of array, for ex.
[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.