0

I have created a tree, in Angular, from an array with property like id and parentId, using the following algorithm:

  public setTree(_searchResponses):void{
    let treeSearchResponses: Tree[] = [];
    _searchResponses.map((searchResponse) => {
      let treeNode:Tree = new Tree();
      treeNode.id = searchResponse.codElemento;
      treeNode.parentId = searchResponse.codElementoPadre;
      treeNode.name = searchResponse.codElemento;
      treeNode.isExpanded = true;
      this.nodeCounter++;
      treeSearchResponses.push(treeNode)
    });

    const nest = (items, id = null, link = 'parentId') =>
      items
        .filter(item => item[link] === id)
        .map(item => ({ ...item, children: nest(items, item.id) }));

    this.treeNodes =  nest(treeSearchResponses);
  }

After doing that, I used an angular library to visualize the tree and modify it using drag&drop (for example I could add or remove some elements, or move the elements, etc), so the tree structur (the treeNodes) can change.

Afted doing that I should be able to recreate an array like the one I used to generate the tree, in order to save it.

I tried using foreach or while, but I'm not able to iterate in the tree structure, in order to visit every node, how could I generate a "reverse algorithm" to do that?

2 Answers 2

1

Reverse Algorithm for the tree formed by your code.

this.searchResponse = [];
function setSearchResponse(treeNode) {
    if (treeNode == null || treeNode == undefined) {
        return;
    }
    treeNode.forEach(node=>{
        this.searchResponse.push({
            codElemento: node.id,
            codElementoPadre: node.parentId
        })

        if (node.children !== null || node.children !== undefined)
            setSearchResponse(node.children);
    }
    )
}
Sign up to request clarification or add additional context in comments.

1 Comment

as I understood nodes can be dragged around the tree, so node.parentId could be wrong at the moment of iterating, but that could be a false expectation
1

tree is a structure that can easilly be traversed by a recursive function. also iterator is a js feature that allows to easilly emit items while traversing anything:

function* treeItems(node: Tree, parentId: string) {
  yield {codElemento: node.id, codElementoPadre: parentId};
  for(let child of node.children) yield* treeItems(child, node.id);
}

// usage
const flatArray = [...treeItems(this.treeNodes)];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.