How to fill the data of a tree-shaped element?

Asked

Viewed 113 times

1

I have an element p:tree of Primefaces, and I would like to fill it with existing data in a ArrayList.

Actually I’d just like to get an idea about what the algorithm might be that does this.

Objective:

The idea is to represent the "Data List" data in an element with the tree structure, specifically the p:tree (I believe that the image expresses the idea better):

inserir a descrição da imagem aqui

Any idea is welcome, it does not necessarily have to be a specific answer in relation to the platform, only an algorithm would serve.

  • Closely related issue, but not equal (in my view): http://answall.com/questions/2425/comormodelr-structura-datastructures-em-%C3%A1rvore-using-a-database-relate

  • What exactly is causing you difficulties? Supposing that given a knot you can add children to it (I don’t know Primefaces, but that example suggests that yes), my suggestion is for each item of the ArrayList you add an entry in a HashMap<Integer,TreeNode> associating the ID of the die with the node you created for it; then you take the top node of that same die, query the same map to get the parent node, and then add the child to the parent (or root, if there is no parent). It’s +- that or something else?

  • It’s + or - that’s right.Thanks for the idea.

1 answer

1

Just to not be unanswered, I decided to implement the algorithm in Javascript.

The comments explain better than an introductory paragraph, but I note here that this code can be easily adapted to any language, especially object-oriented ones. I avoided unnecessary class statements and complications, but included a function to print the result, just for the convenience of anyone who wants to test the code (just click on Execute code snippet).

Note that this solution is based on the fact that the nodes are described in the data array (dados), increasing sequence of their codes (ID’s).

The algorithm, meanwhile, can be easily adapted to support arbitrary sequences of description, provided that the code is entered in the 3rd column of the array, for example; simply include the code as a secondary value (id: dados[i][2], in this new example), within the structure of each node (1st loop of the algorithm), and then perform the comparison (if, in the 2nd loop) from this stored code, instead of using the loop index (i+1).

// Array de dados. A primeira coluna é o valor do nó; a segunda, indica o nó pai.
var dados = [
    [ "Dado 1", null ],
    [ "Dado 2", 1    ],
    [ "Dado 3", 1    ],
    [ "Dado 4", 2    ],
    [ "Dado 5", 2    ],
    [ "Dado 6", 4    ],
    [ "Dado 7", 5    ]
];

// Declaração do array que conterá cada nó:
var nos = [];

// Transformação de cada elemento do array de dados em um nó (ainda sem relacionamento):
for(var i = 0; i < dados.length; i++){
    nos.push({
        valor: dados[i][0],
        filhos: []
    });
}

/*
  CRIAÇÃO DOS RELACIONAMENTOS:
  A ideia é que cada nó procure por seus filhos no array de dados; como o índice de um
  elemento no array de dados é exatamente o mesmo índice do seu respectivo nó, no array
  de nós, basta que cada nó procure no array de dados quais deles fizeram referência a ele:
*/
for(var i = 0; i < nos.length; i++){
    for(var j = 0; j < dados.length; j++){
        if(i+1 == dados[j][1]) nos[i].filhos.push(nos[j]); // i+1 porque os índices começam em 0.
    }
}

// Imprime o resultado:
print(nos[0], "&rarr; "); // nos[0] representa o nó raiz da árvore.


//==============================================================================================


/*
  EXTRA:
  Função recursiva para imprimir a árvore (com busca em profundidade), apenas para visualizar
  o resultado.
  Varia bastante de linguagem para linguagem, no JavaScript está é uma das formas de fazer:
*/
function print(no, recuo){
    var p = document.createElement("p"); // Cria um parágrafo HTML.
    p.innerHTML = recuo + no.valor;      // Seta o texto deste parágrafo para indentação + valor.
    document.body.appendChild(p);        // Joga o parágrafo na tela (torna visível).
    // Se possuir filhos...
    if(no.filhos.length > 0) for(var i = 0; i < no.filhos.length; i++){
        // ...imprime cada um deles, com um recuo 8 espaços maior:
        print(no.filhos[i], "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + recuo);
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.