Skip to content

Instantly share code, notes, and snippets.

@daifu
Last active December 16, 2015 15:49
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 daifu/5458228 to your computer and use it in GitHub Desktop.
Save daifu/5458228 to your computer and use it in GitHub Desktop.
Pretty Print a Binary Search Tree
static class Wrapper {
TreeNode node;
int level;
Wrapper(TreeNode node, int level) {
this.node = node;
this.level = level;
}
}
static int skip;
public void pretty() {
skip = 0;
if(root == null) {
System.out.println("Empty Tree!");
return;
}
setPos(root); // Find line position for each node
pretty(root); // level-order traversal display the nodes
}
public void setPos(TreeNode node) {
if(node != null) {
setPos(node.left);
node.util = skip; // Store skip value in util data member
skip += 2; // Update for printing THIS node
setPos(node.right);
}
}
public void pretty(TreeNode) {
Queue<Wrapper> que = new Queue<Wrapper>();
int position = 0, // position in output line
level = 1, // level being processed
current; // value for node ABOUT to process
que.offer(new Wrapper(node, level));
while(!que.isEmpty()) {
Wrapper item = queue.remove();
node = item.node;
current = item.level;
if(node.left != null)
queue.offer(new Wrapper(node.left, current+1));
if(node.right != null)
queue.offer(new Wrapper(node.right, current+1));
if(current != level) {
System.out.println();
}
for(; position < node.util; position++) {
System.out.print(" ");
System.out.print("%2", node.data);
position += 2;
}
System.out.println(); // Final line termination
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment