Upload
leo-malone
View
222
Download
6
Tags:
Embed Size (px)
Citation preview
Drawing Binary Tree (Console-based)
In a rectangular grid, each cell is denoted by a pair (level, column)
A rectangular grid
0 1 2 3 4
0 1
: (0, 1)
A
B C
D E
A
B C
D E
Column: 0 1 2 3 4 0
1 2
level
Graphical drawing Console-based drawing
If we can denote each node using a pair (level, column), we can draw a tree in thegrid.
The issue is how do we denote each node using a pair?
A
B C
D E
A
B C
D E
Column: 0 1 2 3 4 0
1 2
level
The in-order scan: B, D, A, E, C Column order
Question: What is the in-order traverse of this tree?
A
B C
D E
A
B C
D E
Column: 0 1 2 3 4 0
1 2
level
Level: 0
To observe the level order is straight forward.
Level: 1 Level: 1
Level: 2 Level: 2
Solve the ProblemInput: a tree with node structureDraw it in a way such that each node can be
denoted by a pair (level, column) in a grid
Left
Value
Right
AlgorithmGiven a tree T with node structureBuild a new tree S with node structure
Use In-order scan to traverse tree TDraw tree based on the newly built tree
A queue is needed for a level-order scan.
Left Value
Right
Left Value Level Column Right
Example of building new tree
A
B C
D E
Column: 2Level: 0
Column: 0Level: 1
Column: 4Level: 1
Column: 1Level: 2
Column: 3Level: 2
A
B C
D E
Example of drawing tree
A
B C
D E
Draw the tree in the order of A, B ,C , D ,EAdd indentation(Space) when needed.
Example of drawing tree
A
B C
D E
In order to get the order “A, B ,C , D ,E ”.
APush A
Example of drawing tree
A
B C
D E
In order to get the order “A, B ,C , D ,E ”.
A B
Push children of A
Example of drawing tree
A
B C
D E
In order to get the order “A, B ,C , D ,E ”.
A B C
Push children of A
Example of drawing tree
A
B C
D E
In order to get the order “A, B ,C , D ,E ”.
B C
{A}
Pop A
Example of drawing tree
A
B C
D E
In order to get the order “A, B ,C , D ,E ”.
B C
{A}
Example of drawing tree
A
B C
D E
In order to get the order “A, B ,C , D ,E ”.
B C D
{A}
Example of drawing tree
A
B C
D E
In order to get the order “A, B ,C , D ,E ”.
C D
{A, B}
Pop(B)
Example of drawing tree
A
B C
D E
In order to get the order “A, B ,C , D ,E ”.
C D E
{A, B}
Example of drawing tree
A
B C
D E
In order to get the order “A, B ,C , D ,E ”.
C D E
{A, B,C}
Example of drawing tree
A
B C
D E
In order to get the order “A, B ,C , D ,E ”.
D E
{A, B,C}
Example of drawing tree
A
B C
D E
In order to get the order “A, B ,C , D ,E ”.
D E
{A, B,C, D}
Example of drawing tree
A
B C
D E
In order to get the order “A, B ,C , D ,E ”.
{A, B,C, D, E}
Example of drawing tree
A
B C
D E
Indentations can be any size of space. I used 1 space for each cell in the grid.