Woody Briggs Woody Briggs - 3 months ago 29
Javascript Question

General Tree Post Order Traversal

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?

Answer

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.