Skip to content

Instantly share code, notes, and snippets.

@bisignam
Created April 7, 2017 19:43
Show Gist options
  • Save bisignam/f4e856f0cddd9ee06d7719739ce37dc3 to your computer and use it in GitHub Desktop.
Save bisignam/f4e856f0cddd9ee06d7719739ce37dc3 to your computer and use it in GitHub Desktop.
Print binary tree
public void printTree(Node root) {
if (root.right != null) {
printTree(root.right, true, "");
}
System.out.println(root.data);
if (root.left != null) {
printTree(root.left, false, "");
}
}
// use string and not stringbuffer on purpose as we need to change the indent at each recursion
private void printTree(Node root, boolean isRight, String indent) {
if (root.right != null) {
printTree(root.right, true, indent + (isRight ? " " : " | "));
}
System.out.print(indent);
if (isRight) {
System.out.print(" /");
} else {
System.out.print(" \\");
}
System.out.print("----- ");
System.out.println(root.data);
if (root.left != null) {
printTree(root.left, false, indent + (isRight ? " | " : " "));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment