3
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?

1 Answers1

2

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.

GOTO 0
  • 42,323
  • 22
  • 125
  • 158
  • Perfect!! thanks a lot! i knew it had to be done iteratively at this point but my knowledge of javascript is poor at the moment, the forEach is a trick i shall keep in my books Thanks! – Woody Briggs Aug 13 '16 at 22:26