Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Perform level order traversal for a tree,
- * aka Breadth First Search.
- *
- * @param tree {BinarySearchTree}
- * @returns {boolean|[]}
- */
- function bfs(tree) {
- if (!tree.root) {
- return false;
- }
- return bfsHandler(tree.root);
- }
- function bfsHandler(root) {
- // Use an array as a queue by using some of
- // built-in array functions like push and shift.
- let queue = [];
- // Use an array to track the traversed nodes for
- // printing out using console.
- let traversedNodes = [];
- // Enqueue the root node into the queue.
- queue.push(root);
- while (queue.length) {
- let current = queue[0];
- traversedNodes.push(current);
- if (current.left) {
- queue.push(current.left);
- }
- if (current.right) {
- queue.push(current.right);
- }
- // Dequeue the front element in the queue.
- queue.shift();
- }
- return traversedNodes;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement