Skip to content
Advertisement

How to create a tree by using nodes that point to next brother in Java?

I made a class (shown below) to create a tree where nodes point to the first brother on his own right and the first son (graphically the one on the extreme left).
How can i generate and link nodes correctly inside a for loop?

So the first iteration of the loop needs to generate and link the first son node to the parent node, while each of the following iterations should generate and link a new node to be the brother of the previous one

final class Node { 
    private Node firstSon = null;
    private int data;
    private Node brotherDX = null;

    public Nodo(Nodo firstSon, int data, Nodo brotherDX) {
        this.data = data;
        this.brotherDX = brotherDX;
        this.firstSon = firstSon;
    }
}
public class MyClass {
    private Node rootNode = new Node(null, 0, null)
    
    //for cicle goes here
}

I’ll attach a quick drawing of how the tree should work : The nodes contain:
LIGHT BLUE – link to first son
WHITE – data of the node
GREEN – link to brother on the right
The purple lines show what the actual shape of the tree should be in terms of parenting of the nodes.

Advertisement

Answer

So you want a data structure where there is one parent node (with the firstSon pointer pointing towards the first “child” node) and a lot of child nodes, each of which point to the next using the brotherDX pointer, so either brotherDX or firstSon goes unused? Wouldn’t it be a lot easier to just have one pointer for both (which would, incidentally, be a singly linked list)?

Either way, the logic for adding nodes the way you want them to is fairly simple:

Node start = new Node(null, 0, null);
Node temp = new Node(null, 1, null);
start.firstSon = temp;
for(int i=2;i<=AMOUNT_OF_NODES;i++){
    temp.brotherDX = new Node(null, i, null);
    temp = temp.brotherDX;
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement