-
-
Save fizalihsan/cc21a12af3d751baf7ec8dac57ea8775 to your computer and use it in GitHub Desktop.
Binary Tree - Preorder, Inorder, Postorder traversal examples
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 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