1. Introduction
In the realm of binary trees, traversal techniques are the methods by which we visit each node in the tree exactly once, while processing or examining its value. The three most commonly used traversal techniques are: Inorder, Preorder, and Postorder.
1. Inorder (Left, Root, Right): First traverse the left subtree, then visit the root, and finally the right subtree.
2. Preorder (Root, Left, Right): Visit the root first, then traverse the left subtree, and finally the right subtree.
3. Postorder (Left, Right, Root): Traverse the left subtree first, then the right subtree, and visit the root last.
2. Program Steps
1. Define the structure of the binary tree using a TreeNode class.
2. Implement the three traversal methods:
a. For Inorder: Traverse left subtree, visit the root, and traverse the right subtree.
b. For Preorder: Visit the root, traverse the left subtree, and traverse the right subtree.
c. For Postorder: Traverse the left subtree, traverse the right subtree, and visit the root.
3. In the main method, create a sample tree and perform all three traversals on it.
3. Code Program
class TreeNode {
int value;
TreeNode left;
TreeNode right;
TreeNode(int value) {
this.value = value;
left = null;
right = null;
}
}
public class TreeTraversals {
public static void inorder(TreeNode root) {
if (root == null) return;
inorder(root.left);
System.out.print(root.value + " ");
inorder(root.right);
}
public static void preorder(TreeNode root) {
if (root == null) return;
System.out.print(root.value + " ");
preorder(root.left);
preorder(root.right);
}
public static void postorder(TreeNode root) {
if (root == null) return;
postorder(root.left);
postorder(root.right);
System.out.print(root.value + " ");
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
System.out.println("Inorder traversal: ");
inorder(root);
System.out.println("\nPreorder traversal: ");
preorder(root);
System.out.println("\nPostorder traversal: ");
postorder(root);
}
}
Output:
Inorder traversal: 4 2 5 1 3 Preorder traversal: 1 2 4 5 3 Postorder traversal: 4 5 2 3 1
4. Step By Step Explanation
1. The TreeNode class encapsulates the structure of individual nodes in our binary tree. Each node has a value, a left child, and a right child.
2. The inorder, preorder, and postorder methods are recursive functions, each embodying its respective traversal technique.
3. Each traversal method follows a pattern. For instance, in inorder, we first traverse the left child, print the current node's value, and then traverse the right child.
4. Similarly, preorder involves printing the root before traversing the children, while postorder prints the root after traversing both children.
5. The main method showcases a simple tree and its traversal using all three techniques.