0

I wanted to know the previous visited node from tree. trying with below example

var TreeModel = require('tree-model');
tree = new TreeModel();

rootMain = tree.parse({
    id: 1,
    children: [
        {
            id: "11",
            children: [{id: "111"}]
        },
        {
            id: "12",
            children: [{id: "121"}, {id: "122"}]
        },
        {
            id: "13"
        }
    ]
});

If suppose I traverse to the node 121 and 122 I wanted the parent node then it should return me the 12 If suppose I traverse to the node 111 I wanted the parent node then it should return me the 11 If suppose I traverse to the node 13 I wanted the parent node then it should return me the 1

Mukesh S
  • 367
  • 5
  • 19

2 Answers2

1

While traversing the tree you can get the parent of the current node with node.parent.

rootMain.walk(node => {
  console.log('node id:', node.model.id);

  if(node.parent) {
    console.log('parent node id:', node.parent.model.id);
  }
});
jgranstrom
  • 576
  • 5
  • 13
0

This logs the desired parent id

var parent_id;

rootMain.walk(function (node) {

    var current_id = node.model.id;
    if (node.model.id === 121) 
        console.log(parent_id);
        return true;
    parent_id = current_id;
});
THEOS
  • 59
  • 5