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 }
遞歸遍歷孩子,依底向上、左至右順序
補:依底向上、左到右順序不一定是層次最深的排前面。可以用層序遍歷倒過來記錄: