一般树Post顺序遍历

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);

这是我在 javascript 中使用 JSON 树进行递归 post 顺序遍历的代码。

我将如何调整此代码以处理节点中的 N 个子节点?

这应该可以满足您的要求:只需将对 postOrder 的调用替换为 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);

我还会将打印 root 名称的行移动到递归打印子名称的调用之前,但这可能与您的用例不匹配。