Site icon

Print paths from root to leaf nodes in binary tree (Java/ recursive)

Fig 1: Root to leaf path binary tree

The root to leaf paths in a binary tree are as follows:

S. No.Root to leaf path Value
1A -> B -> D 100->50->25
2A -> B -> E 100->50->80
3A -> C -> F 100->150->125
4A -> C -> G 100->150->160

Brief algorithm to print root to leaf paths is as follow:

Fig 2: Root to leaf paths

Algorithm: print root to leaf paths in java (recursive)

Code- print all paths from root to leaf nodes in a binary tree

1.) Root2Leaf  Class:

package org.learn.Question;

import java.util.Arrays;
import org.learn.PrepareTree.Node;

public class Root2Leaf {
	private static int nPath ;
	public static void root2LeafPath(Node root, int[] path) {
		nPath = 0;
		processPath(root, path,0);
	}
	private static void processPath(Node root, int[] path,int index) {
		if(null == root) {
			return;
		}
		path[index++] = root.data;
		if(root.left == null && root.right == null) {
			print(path,index);
			return;
		}
		processPath(root.left,path,index);
		processPath(root.right,path,index);		
		return;
	}
	
	private static void print(int[] path,int index) {
		System.out.printf("Root to Leaf path %d : ",++nPath);
		System.out.println(Arrays.toString(Arrays.copyOf(path,index)));
		return;
	}
}

2.) Node class:

package org.learn.PrepareTree;

public class Node {
	public int data;
	public Node left;
	public Node right;

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

	public Node() {
		this.left = null;
		this.right = null;
	}
}

3.) App Class:

package org.learn.Client;

import org.learn.Question.Node;
import org.learn.Question.Root2Leaf;

public class App {
	public static void main(String[] args) {
		// root level 0
		Node A = Node.createNode(100);
		// Level 1
		Node B = Node.createNode(50);
		Node C = Node.createNode(150);
		// Level 2
		Node D = Node.createNode(25);
		Node E = Node.createNode(80);
		Node F = Node.createNode(125);
		Node G = Node.createNode(160);

		// connect Level 0 and 1
		A.left = B;
		A.right = C;
		// connect level 1 and level 2
		B.left = D;
		B.right = E;
		C.left = F;
		C.right = G;

		int[] path = new int[512];
		Root2Leaf.root2LeafPath(A, path);
	}
}

Output – root to leaf path in a binary tree (recursive)

Root to Leaf path 1 :  100 50 25
Root to Leaf path 2 :  100 50 80
Root to Leaf path 3 :  100 150 125
Root to Leaf path 4 :  100 150 160

Download code – print root to leaf path binary tree recursive algorithm java

 

Exit mobile version