1

I'm working on a project to create a tree with more than 2 child nodes. I get that when creating a binary tree, we can just create a left node and a right node to act as children, but when I've looked online for help in creating a tree, every solution I've found talks about creating a binary tree. I understand that part of creating a tree means you need to create an array or arraylist of children nodes, but I don't understand how I'm going to put data into that array or how I'm going to 'connect' the array of children nodes to my parent node?

Here's the code I have at the moment. I know it's not a lot, but I'm struggling just starting this project.

class Node
{
    public int data; //data for storage
    public Node[] children;//array will keep children
    public Node parent;//parent to start the tree

    public Node(, int data)//constructor will store data and children(I think?)
    {
    }
}

public class Tree //main class will implement everything in Node
{
}

How and where do I start this process of connecting my children nodes to my parent/root node?

Arjun Singh
  • 103
  • 2
  • 7

1 Answers1

2

Storing children in list not to have problems with array recreation, but you can use array too. You may also init array directly in the constructor, or when adding first child.

public class Main {

    public static void main(String[] args) {
        Node node = new Node(1)
            .addChild(new Node(2)
                    .addChild(new Node(4))
                    .addChild(new Node(5)))
            .addChild(new Node(3));
    }
}

class Node {
    public int data; //data for storage
    public List<Node> children;//array will keep children
    public Node parent;//parent to start the tree

    public Node(int data) {
        children = new ArrayList<>();
        this.data = data;
    }

    public Node addChild(Node node) {
        children.add(node);
        node.parent = this;
        return this;
    }
}
Vitaliy Moskalyuk
  • 2,463
  • 13
  • 15
  • So in addChild, once you confirm that the children arrayList in the outside is null, you're converting that list of Node objects into an ArrayList? – Arjun Singh Jul 24 '20 at 18:22
  • 1
    @ArjunSingh, you can init List directly in constructor, so you'll have empty or non-empty list, which will never be null. In my code list is created when node added, so if list is not null - there will be definitely at least 1 item. But this is just how I wrote, and it could be changed depending on your needs. – Vitaliy Moskalyuk Jul 24 '20 at 18:25
  • Thanks! That makes sense. – Arjun Singh Jul 24 '20 at 18:26
  • 1
    This is the base idea, which you can adjust. – Vitaliy Moskalyuk Jul 24 '20 at 18:26