Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 773
Woody Briggs Avatar asked Dec 06 '25 18:12

Woody Briggs


1 Answers

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.

like image 90
GOTO 0 Avatar answered Dec 09 '25 21:12

GOTO 0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!