Traversing a Tree data structure with recursion

suggest change

Consider the Node class with three members, data, a left-child pointer, and a right-child pointer, as below.

public class Node {
    public int data;
    public Node left;
    public Node right;
    
    public Node(int data){
        this.data = data;
    }
}

We can traverse the tree constructed by connecting multiple Node objects, as below. The traversal is called in-order traversal of a tree.

public static void inOrderTraversal(Node root) {
        if (root != null) {          
            inOrderTraversal(root.left); // traverse left sub tree
            System.out.print(root.data + " "); // traverse current node
            inOrderTraversal(root.right); // traverse right sub tree
        }
    }

As demonstrated above, using recursion we can traverse the tree data structure without using any other data structure which is not possible with the iterative approach.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents