Tree Iteration
by Nirvanachain
JavaScript
var data = {
data: 'A', // non-leaf node
children: [
{
data: 'A.A', // leaf node
},
{
data: 'A.B', // leaf node
},
{
data: 'A.C', // non-leaf node
children: [
{
data: 'A.C.A', // leaf node
},
{
data: 'A.C.B', // leaf node
},
]
}
]
}
function convertTreeToList(root) {
var stack = [];
var arr = [];
var hashMap = {};
stack.push(root)
while (stack.length !== 0) {
var node = stack.pop();
if (!node.children) {
if (!hashMap[node.data]) {
hashMap[node.data] = true;
arr.push(node)
}
} else {
for (var i = node.children.length -1; i >= 0; i--) {
stack.push(node.children[i])
}
}
}
return arr;
}
convertTreeToList(data)