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

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

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

4

1 回答 1

2

这应该可以满足您的要求:只需将您的调用替换postOrderroot.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递归打印子名称的调用之前移动打印名称的行,但这可能与您的用例不匹配。

于 2016-08-13T22:19:21.013 回答