Printing BST
-
Hi Folks, I Need to print a Binary TREE like so: 10 / \ 5 15 / / \ 2 14 17 I have the code to add to the tree and that all works ok and i have a method to print out the full tree starting at the root, then all the left nodes then the right nodes:
public void ShowTree(Node T)
{
if (T != null)
{
Console.Write(T.DATA+ "\n");
ShowTree(T.LEFT);
ShowTree(T.RIGHT);
}}
I have tried something like this:
private static void ShowTree(Node tp, int spaces)
{
int i = 0;if (tp != null) { ShowTree(tp.left, spaces + 3); for (i = 0; i < spaces; i++) { Console.Write(" "); } Console.WriteLine(tp.data); ShowTree(tp.right, spaces + 3); } }
And a few other approaches but i cannot get it to do as i want. Any suggestions on how i can do this?
-
Hi Folks, I Need to print a Binary TREE like so: 10 / \ 5 15 / / \ 2 14 17 I have the code to add to the tree and that all works ok and i have a method to print out the full tree starting at the root, then all the left nodes then the right nodes:
public void ShowTree(Node T)
{
if (T != null)
{
Console.Write(T.DATA+ "\n");
ShowTree(T.LEFT);
ShowTree(T.RIGHT);
}}
I have tried something like this:
private static void ShowTree(Node tp, int spaces)
{
int i = 0;if (tp != null) { ShowTree(tp.left, spaces + 3); for (i = 0; i < spaces; i++) { Console.Write(" "); } Console.WriteLine(tp.data); ShowTree(tp.right, spaces + 3); } }
And a few other approaches but i cannot get it to do as i want. Any suggestions on how i can do this?
The secret to drawing a binary tree is to start with the leaves. A depth-first search will go through the leaves in order from left to right. Increment each leaf's X coordinate to allow space for the previous leaf. The Y coordinate comes from the depth of the leaf's level. When the coordinates have been assigned to all of an interior node's sons, you can use them to position the interior node in the middle, above its sons. When all nodes have coordinates, just cycle through them and draw them.
"Microsoft -- Adding unnecessary complexity to your work since 1987!"
-
The secret to drawing a binary tree is to start with the leaves. A depth-first search will go through the leaves in order from left to right. Increment each leaf's X coordinate to allow space for the previous leaf. The Y coordinate comes from the depth of the leaf's level. When the coordinates have been assigned to all of an interior node's sons, you can use them to position the interior node in the middle, above its sons. When all nodes have coordinates, just cycle through them and draw them.
"Microsoft -- Adding unnecessary complexity to your work since 1987!"
Wow, couldn't have said it better myself! :) :) Thanks Alan!
April Comm100 - Leading Live Chat Software Provider