Skip to content

Instantly share code, notes, and snippets.

@fizalihsan
Created May 16, 2016 12:12
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 fizalihsan/cc21a12af3d751baf7ec8dac57ea8775 to your computer and use it in GitHub Desktop.
Save fizalihsan/cc21a12af3d751baf7ec8dac57ea8775 to your computer and use it in GitHub Desktop.
Binary Tree - Preorder, Inorder, Postorder traversal examples
public class TreeTraversals {
public static void main(String[] args) {
Node<String> root =
new Node<>("A",
new Node<>("B",
new Node<>("D"), new Node<>("E")
),
new Node<>("C",
new Node<>("F"), new Node<>("G")
)
);
System.out.print("\nPreorder: "); //Preorder: A, B, D, E, C, F, G
preorder(root);
System.out.print("\nInorder: "); // Inorder: D, B, E, A, F, C, G,
inorder(root);
System.out.print("\nPostorder: "); //Postorder: D, E, B, F, G, C, A
postorder(root);
}
private static void preorder(Node root) {
if (root == null) return; // Empty subtree - do nothing
System.out.print(root.getValue() + ", "); // Process root node
preorder(root.getLeft()); // Process all nodes in left
preorder(root.getRight()); // Process all nodes in right
}
private static void inorder(Node root) {
if (root == null) return; // Empty subtree - do nothing
inorder(root.getLeft()); // Process all nodes in left
System.out.print(root.getValue() + ", "); // Process root node
inorder(root.getRight()); // Process all nodes in right
}
private static void postorder(Node root) {
if (root == null) return; // Empty subtree - do nothing
postorder(root.getLeft()); // Process all nodes in left
postorder(root.getRight()); // Process all nodes in right
System.out.print(root.getValue() + ", "); // Process root node
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment