Tree traversal recursive


class BinaryTree {
    private static Node root;
    
    void preOrder(Node root) {
        if(root != null) {
            System.out.print(root.data + " ");
            preOrder(root.left);
            preOrder(root.right);
        }
    }
    
    void inOrder(Node root) {
        if(root != null) {
            inOrder(root.left);
            System.out.print(root.data + " ");
            inOrder(root.right);
        }
    }
    
    void postOrder(Node root) {
        if(root != null) {
            postOrder(root.left);
            postOrder(root.right);
            System.out.print(root.data + " ");
        }
    }
    
	public static void main (String[] args) {
		BinaryTree tree = new BinaryTree();
		root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.left = new Node(6);
        root.right.right = new Node(7);
        
        System.out.println("Pre order :");
        tree.preOrder(root);
        System.out.println("\nIn order :");
        tree.inOrder(root);
        System.out.println("\nPost order :");
        tree.postOrder(root);
	}
	private static class Node {
	    Node left;
	    int data;
	    Node right;
	    public Node(int data) {
	        this.data = data;
	    }
	}
}


Output

Pre order :

1 2 4 5 3 6 7 

In order :

4 2 5 1 6 3 7 

Post order :

4 5 2 6 7 3 1 

Comments

Popular posts from this blog

SQL basic interview question

gsutil Vs Storage Transfer Service Vs Transfer Appliance