var tree = {
"name" : "root",
"children" : [
{
"name" : "first child",
"children" : [
{
"name" : "first child of first",
"children" : []
},
{
"name" : "second child of first",
"children" : []
}
]
},
{
"name" : "second child",
"children" : []
}
]
}
function postOrder(root) {
if (root == null) return;
postOrder(root.children[0]);
postOrder(root.children[1]);
console.log(root.name);
}
postOrder(tree);
Heres my code for a recursive post order traversal in javascript using a JSON tree.
How would I go about adapting this code to handle N children in a node?
This should do what you want: just replace your calls to postOrder with root.children.forEach(postOrder);.
var tree = {
"name" : "root",
"children" : [
{
"name" : "first child",
"children" : [
{
"name" : "first child of first",
"children" : []
},
{
"name" : "second child of first",
"children" : []
}
]
},
{
"name" : "second child",
"children" : []
}
]
}
function postOrder(root) {
if (root == null) return;
root.children.forEach(postOrder);
console.log(root.name);
}
postOrder(tree);
I'd also move the line that prints the root name before the call that prints the children names recursively, but this may not match your use case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With