/Tree

Tree

Node Class

public class Node {
    private int data;
    private ArrayList arraylist;
 
    public Node(int data)
    {
        this.data=data;
        this.arraylist=new ArrayList();
    }

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }

    public ArrayList getArraylist() {
        return arraylist;
    }

    public void setArraylist(ArrayList arraylist) {
        this.arraylist = arraylist;
    }

    @Override
    public String toString() {
        return "Node{" + "data=" + data + ", arraylist=" + arraylist + '}';
    }
}

Tree Example

import java.util.ArrayList;
import java.util.Scanner;

public class TreeExample {

    public static void main(String args[]) {
        Node root = insertElement();
        System.out.println(root);
        print(root);
    }

    private static void print(Node root) {
        if (root != null) {
            System.out.println(root.getData());
            ArrayList array = root.getArraylist();
            for (int i = 0; i < array.size(); i++) {
                print((Node) array.get(i));
            }
        }
    }

    private static Node insertElement() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the element");
        int data = scanner.nextInt();
        Node node = new Node(data);
        System.out.println("Enter no of child");
        int nofchild = scanner.nextInt();
        ArrayList arr = new ArrayList(nofchild);
        node.setArraylist(arr);
        for (int i = 0; i < nofchild; i++) {
            Node newnode = insertElement();
            arr.add(newnode);
        }
        return node;
    }
}