Wednesday, July 15, 2015

print binary tree on x,y coordinate system with no overlap

//examples
   3
 1   5
0 2 4 6

prints as

...3
.1...5
0.2.4.6

  1
 0 5
  4
 3
2

prints as 

.1
0....5
....4
...3
..2
Only x collides. It does not when x for node is node's in-order traversal number. To show tree in 1st quad, offset y by depth.
(n):
    // box x or pass by ref
    (n, x = {x=0}, y = depth(n)-1)
(n, x, y):
    if n == null:
        return
    (n.left, x, y-1)
    print(x.x, y)
    x.x++
    (n.right, x, y-1)

[Hat tip to J]

No comments:

Post a Comment