2017-02-21 8 views
0

트리에서 이전에 방문한 노드를 알고 싶었습니다. 나는 그때 그것을 부모 노드를 원 노드 (111)에 통과한다고 가정하면 나에게 12 을 반환해야 그때 부모 노드를 원 노드 (121, 122)를 통과한다고 가정하면 예를 아래에tree-model-js 이전 노드 ID를 얻는 방법

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" 
     } 
    ] 
}); 

과 노력 나를 돌려 보내야한다 11 만약 내가 노드 13으로 이동했다면 부모 노드를 원했을 때 1을 돌려 주어야한다.

답변

1

트리를 탐색하면서 node.parent으로 현재 노드의 부모를 얻을 수있다.

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

    if(node.parent) { 
    console.log('parent node id:', node.parent.model.id); 
    } 
}); 
+0

감사를 기록합니다 ..! 나를위한 그 일 –

0

이 원하는 부모 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; 
});