How to Pretty Print a Binary Tree?
818038Nov 23 2010 — edited Nov 24 2010I'm trying to display a Binary Tree in such a way:
________26
___13_________2
1_______4 3_________1
(without the underscores)
however I cannot figure out the display method.
class BinaryNode
{
//Constructors
BinaryNode leftChild, rightChild;
Object data;
BinaryNode()
{
leftChild = null;
data = null;
rightChild = null;
}
BinaryNode( Object d, BinaryNode left, BinaryNode right)
{
leftChild = left;
data = d;
rightChild = right;
}
//Height
public static int Height(BinaryNode root)
{
if (root == null)
{
return 0;
}
if ((Height(root.leftChild)) > Height(root.rightChild))
{
return 1 + Height(root.leftChild);
}
return 1 + Height(root.rightChild);
}
//Count
public static int Count(BinaryNode root)
{
if(root==null)
return 0;
return 1 + Count(root.leftChild) + Count(root.rightChild);
}
}
}
//Display
public static void Display(BinaryNode root)
{
int level = 2^(Level(root)-1)
for (int i = 1; i<Height(root)+1; i++)
{
System.out.printf("%-4s%
Display(root, i);
System.out.println();
}
}
public static void Display(BinaryNode root, int level)
{
if (root!=null)
{
if(level==1)
System.out.print(root.data + " ");
else
{
Display(root.leftChild, level-1);
Display(root.rightChild, level-1);
}
}
}
//Level
public static int Level(BinaryNode root)
{
if(root==null)
return 0;
if(root.leftChild == null && root.rightChild == null)
return 1;
return Level(root.leftChild) + Level(root.rightChild);
}
}
Edited by: 815035 on Nov 23, 2010 12:27 PM