function* traverseDFSStack(root) {
if (!root) return;
const stack = [root];
while (stack.length > 0) {
// 1. 取出 Stack 最頂端的節點 (LIFO)
const current = stack.pop();
yield current;
// 2. 從右至左將子節點推入 Stack
// (最後推入的第一個子節點,會在下一輪優先被 pop 出來)
let child = current.lastChild;
while (child) {
stack.push(child);
child = child.previousSibling;
}
}
}
// 使用方式
for (const node of traverseDFSStack(document.body)) {
console.log(node);
}
沒有留言:
張貼留言