function listNode (node) {
if (!(node instanceof Node)) {
throw new TypeError("parameter 1 is not of type 'Node'")
}
return Array.from(node.childNodes || [])
.reduce((cList, cNode) => cList.concat(listNode(cNode)), [])
.concat([node])
}
补:按底向上、左到右顺序并不一定是层次最深的排前面。可以用层序遍历倒过来记录:
function listNode (rootNode) {
if (!(rootNode instanceof Node)) {
throw new TypeError("parameter 1 is not of type 'Node'")
}
var queue = [rootNode, null]
var levelNodes = []
var result = []
while (queue.length > 1) {
var node = queue.shift()
if (node === null) {
queue.push(null)
result = levelNodes.concat(result)
levelNodes = []
continue
}
levelNodes.push(node)
if (node.hasChildNodes()) {
queue = queue.concat(Array.from(node.childNodes))
}
}
if (levelNodes.length > 0) {
result = levelNodes.concat(result)
}
return result
}
递归遍历孩子,按底向上、左到右顺序
补:按底向上、左到右顺序并不一定是层次最深的排前面。可以用层序遍历倒过来记录: