一般树的后序遍历

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个子节点?

你尝试过类似这样的代码吗?for (child in root.children) postOrder(root.children[child]) - Tibrogargan
@Tibrogargan 绝对有效!谢谢!但我认为我更喜欢下面建议的“forEach” :) - Woody Briggs
我也是。我的大脑总是期望Javascript的for .. in结构与其他语言一样工作,但forEach更加简洁。 - Tibrogargan
1个回答

2
这应该可以满足你的需求:只需将你对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名称的那行代码放在递归打印子级名称之前,但这可能不适用于您的用例。


太好了!非常感谢!我知道这一点必须通过迭代来完成,但是我目前对JavaScript的了解很少,forEach是一个技巧,我会记在我的书里。谢谢! - Woody Briggs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接