Created
April 7, 2017 19:43
-
-
Save bisignam/f4e856f0cddd9ee06d7719739ce37dc3 to your computer and use it in GitHub Desktop.
Print binary tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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