Skip to content

Commit c6de2b4

Browse files
committed
Update 589. N 叉树的前序遍历 BFS
1 parent 2ae66f9 commit c6de2b4

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

algorithms/n-ary-tree-preorder-traversal.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,27 @@ var preorder = function (root) {
2626
dfs(root);
2727

2828
return result;
29+
30+
// BFS
31+
// return bfs(root);
2932
};
33+
34+
// BFS
35+
function bfs(root) {
36+
const result = [];
37+
const stack = [];
38+
stack.push(root);
39+
40+
if (!root) return [];
41+
42+
while (stack.length) {
43+
const node = stack.pop();
44+
const children = node.children;
45+
result.push(node.val);
46+
for (let i = children.length - 1; i >= 0; i--) {
47+
stack.push(children[i]);
48+
}
49+
}
50+
51+
return result;
52+
}

0 commit comments

Comments
 (0)