一般树邮政秩序遍历

时间:2016-08-13 22:13:50

标签: javascript tree tree-traversal 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;

  postOrder(root.children[0]);
  postOrder(root.children[1]);

  console.log(root.name);
}

postOrder(tree);

继承我的代码,使用JSON树在javascript中进行递归的订单遍历。

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

1 个答案:

答案 0 :(得分:1)

这应该符合您的要求:只需将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名称的行,但这可能与您的用例不匹配。