# freeCodeCamp Challenge Guide: Use Breadth First Search in a Binary Search Tree

**URL:** <https://forum.freecodecamp.org/t/freecodecamp-challenge-guide-use-breadth-first-search-in-a-binary-search-tree/301718>\
**Category:** freeCodeCamp Contributors\
**Tags:** guide\
**Created:** [August 3, 2019, 5:39pm UTC](https://forum.freecodecamp.org/t/freecodecamp-challenge-guide-use-breadth-first-search-in-a-binary-search-tree/301718 "2019-08-03T17:39:34Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![camperbot](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/camperbot/32/18364_2.png) [@camperbot](https://forum.freecodecamp.org/u/camperbot)\
**Post date:** [August 3, 2019, 5:39pm UTC](https://forum.freecodecamp.org/t/freecodecamp-challenge-guide-use-breadth-first-search-in-a-binary-search-tree/301718/1 "2019-08-03T17:39:34Z")

</div>

# [Use Breadth First Search in a Binary Search Tree](https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/use-breadth-first-search-in-a-binary-search-tree)

* * *

## Solutions

> **Solution 1 (Click to Show/Hide)**
>
> ```javascript
> var displayTree = tree => console.log(JSON.stringify(tree, null, 2));
> 
> function Node(value) {
> this.value = value;
> this.left = null;
> this.right = null;
> }
> 
> function BinarySearchTree() {
> this.root = null;
> // Only change code below this line
> function traverse(direction, root) {
> const queue = [root];
> const results = [];
> 
> function pushIfThere(node, queue) {
> if (node) queue.push(node);
> }
> 
> while (queue.length > 0) {
> const node = queue.shift();
> results.push(node.value);
> if (direction === "level") {
> // Level order: left to right
> pushIfThere(node.left, queue);
> pushIfThere(node.right, queue);
> } else {
> // Reverse level order: right to left
> pushIfThere(node.right, queue);
> pushIfThere(node.left, queue);
> }
> }
> 
> return results;
> }
> 
> // Level order traversal
> this.levelOrder = function() {
> if (!this.root) return null;
> 
> return traverse("level", this.root);
> }
> 
> // Reverse level order traversal
> this.reverseLevelOrder = function() {
> if (!this.root) return null;
> 
> return traverse("reverseLevel", this.root);
> }
> // Only change code above this line
> }
> 
> ```

---

<div class="post-metadata">

**Author:** ![ILM](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/ilm/32/363239_2.png) [@ILM](https://forum.freecodecamp.org/u/ILM)\
**Post date:** [January 8, 2025, 3:51pm UTC](https://forum.freecodecamp.org/t/freecodecamp-challenge-guide-use-breadth-first-search-in-a-binary-search-tree/301718/2 "2025-01-08T15:51:11Z")

</div>

Closed on January 8, 2025, 3:51pm UTC


