Javascript Implementation of Calculating Tree Node Path

  javascript

The tree structure is as follows:

const tree = [
{
id: '00',
Name:' Nanjing University of Technology',
children: [
{
id: '0001',
Name:' college of chemical engineering',
children: [
{
id: '000101',
Name:' Organic Chemistry',
},
{
id: '000102',
Name:' Inorganic Chemistry',
children: [
{
id: '00010201',
Name:' inorganic group 1',
},
{
id: '00010202',
Name:' Inorganic 2 Groups',
}
]
}
]
},
{
id: '0002',
Name:' computer institute',
children: [
{
id: '000201',
Name:' hardware institute',
},
{
id: '000202',
Name:' software institute',
children: [
{
id: '00020201',
Name: 'Java college'
},
{
id: '00020202',
Name: 'C# college'
}
]
}
]
}
]
}
];

The main algorithms are as follows:

function makePath(tree, target) {
 
 var done = false, path = [];
 
 function traverse(tree, target) {
 
 for (let i = 0;   i < tree.length;  i++) {
 const node = tree[i];
 if (!  done) {
 if (i > 0) {
 path.pop();
 }
 path.push(node.id);
 if (node.id === target) {
 done = true;
 return;
 } else {
 let children = node.children;
 if (children) {
 traverse(children, target);
 }
 }
 }
 }
 
 if (!  done) {
 path.pop();
 }
 
 return;
 };
 
 traverse(tree, target);
 
 return path;
 };
makePath(tree, '000101');

Running results:

[ '00', '0001', '000101' ]

Thank you for reading. In addition, I’m here to help my friends raise funds for love. I hope everyone can give some love. My friend’s mother is suffering from rectal cancer. She is currently receiving treatment in Beijing Armed Police General Hospital. Please leave a message and leave your contact information. Thank you in the future!

clipboard.png