As the title says, start from a node and traverse downward until all nodes are traversed. Arrange the deepest nodes at the front and convert these nodes into an array. How to achieve this?
仅有的幸福2017-06-26 10:53:49
Traverse the children recursively, in order from bottom to top, left to right
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])
}
Note: The order from bottom to top and left to right does not necessarily mean the deepest layer is in front. You can use layer sequence traversal to record in reverse:
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
}