Skip to content

Instantly share code, notes, and snippets.

@javajosh
Created October 27, 2017 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javajosh/1212cbc6bcb21fe0c4519d9198bafdd0 to your computer and use it in GitHub Desktop.
Save javajosh/1212cbc6bcb21fe0c4519d9198bafdd0 to your computer and use it in GitHub Desktop.
** Visualizing Binary Trees in ASCII **
1 Let's try something different. The left child goes to the right.
/ \
2 3 <--- No room for 3.left 1 2 4 7
/ \ \ 3 9
4 5 6 5 <-- The oddness is here because we had to skip a row.
/ \ 6 But there is no ambiguity!
7 8 <--- Width totally determined by leaves! 8
This is a variant, where the right child goes to the right, left goes down (skipping occupied rows)
1 3 6 8
1 2 5
/ \ <-- widen this 4
2 3 <-- and this 7
/ \ / \ 9 <-- This is the oddness here...again 5 and 9 want to collide!
4 5 9 6 <--- and 5.right and 9.left can still collide!
/ \ If we keep track of the count of nodes, and the count of left and right, then we can
7 8 allocate a static int[left_count][right_count] array for this representation. Alternatively we can use
dynamic structure. The static structure may waste space depending on the shape.
There is a question: why is 5 the first child of 2 and not the second child of 3?
That is because it would have been on a new row!
1 3 6 8
2
4
7
1 An alternative visualization of a tree, where children are indented. 9
2 Avoids ALL collisions but still makes siblings seem far apart 5
4
7 Okay but what if 2 has first children?
5 1 3 6 8
3 2 a b
9 4
6 7
8 9 <-- is this a branch of 3 or a?
5 <-- is this a branch of b or 6? We can tell in a sequence, but not in a snapshot
One option is to use the space to point to the parent.
1 3 6 8
2 a b
4
7
a 9 <-- 9 follows a, not 3.
6 5 <-- 5 follows 6, not b.
...Just realized I did it wrong. each branch should duplicate the parent in that column.
Otherwise the parent is ambiguous.
1 2 3 4 1234
1 5 6 156
2 7 8 1278
5 9 a 159a
7 b c d 127bcd
5 e f 15ef
c g 127bcg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment