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])
? - Tibrogarganfor .. in
结构与其他语言一样工作,但forEach更加简洁。 - Tibrogargan