Here's an example pseudo code to do this. The main idea is to walk the tree in stages, printing all the nodes in each layer on one line. Each node is divided twice as much space as the nodes below it. Since the tree does not have the same depth, it is artificially supplemented by virtual nodes that occupy spaces where the nodes do not exist.
measure the depth of the tree, call that D have two queues, called Q1 and Q2 enque the top node of the tree in Q1 for (i = D; --i>=0; ){ foreach node in Q1 { on first iteration of this inner loop, print 2^i - 1 spaces, else print 2^(i+1) - 1 spaces. if node == null print blank else print node.value if node.left exists enque node.left in Q2 else enque null in Q2 if node.right exists enque node.right in Q2 else enque null in Q2 } copy Q2 to Q1 clear Q2 print end-of-line }
Each printed space represents the width of one numeric field. Suppose the tree has a depth of D = 4. Then the print will look like this:
source share