Java – How to get recursively get all leaves of a Tree Structure in Java

javarecursiontree

I have a Database Table of a Tree Nodes as below. I want to make a ArrayList in Java out of these Tree Nodes. the Arraylist will recursively fetch all the Tree Nodes in a Recursive Format in Java.

Input:

Database Table

Name            ID      Parent_ID
Parent          1   
Child-1         2           1
Child-1.1       3           2
Child-1.1.1     4           3
Child-2         5           1
Child-3         6           1
Child-1.1.1.1   7           4
Child-1.2       8           2

I want to make an ArrayList of the above table in the below Java format where Sub is list of the Child Nodes, if no Child Node then Sub is Null.

public class Node {

    private String id;
    private String name;
    private String type;
    private String value;
    private List<Node> sub;
}

Output:

  1. Parent
    • Child-1
      • Child-1.1
        • Child-1.1.1
          • Child-1.1.1.1
      • Child-1.2
    • Child-2
    • Child-3

Can someone please help in creating a recursive function in Java to implement the above.

Best Answer

Recursive function:

public void printTree(Node tree,int num)
{
    if(tree==null || tree.getSub()==null)return;
    for(Node n : tree.getSub())
    {
    System.out.println(new String(new char[num]).replace("\0", "   ")+"*"+n.getName());
printTree(n,num+1);
}
}

public void callRec(Node tree)
{
    System.out.println(tree.getName());
    printTree(tree,1);
}

The result will be:

Parent
*Child-1
  *Child-1.1
     *Child-1.1.1
        *Child-1.1.1.1
  *Child-1.2
*Child-2
*Child-3