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

**URL:** <https://forum.freecodecamp.org/t/freecodecamp-challenge-guide-use-depth-first-search-in-a-binary-search-tree/301719>\
**Category:** freeCodeCamp Contributors\
**Tags:** guide\
**Created:** [August 3, 2019, 5:39pm UTC](https://forum.freecodecamp.org/t/freecodecamp-challenge-guide-use-depth-first-search-in-a-binary-search-tree/301719 "2019-08-03T17:39:41Z")\
**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-depth-first-search-in-a-binary-search-tree/301719/1 "2019-08-03T17:39:41Z")

</div>

# [Use Depth First Search in a Binary Search Tree](https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/use-depth-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
> // In-order traversal
> this.inorder = function() {
> if (!this.root) return null;
> 
> function traverse(node) {
> if (!node) return [];
> const nodes = traverse(node.left); // Left
> nodes.push(node.value); // Root (in-order)
> nodes.push(...traverse(node.right)); // Right
> return nodes;
> }
> 
> return traverse(this.root);
> }
> 
> // Pre-order traversal
> this.preorder = function() {
> if (!this.root) return null;
> 
> function traverse(node) {
> if (!node) return [];
> const nodes = [node.value]; // Root (pre-order)
> nodes.push(...traverse(node.left)); // Left
> nodes.push(...traverse(node.right)); // Right
> return nodes;
> }
> 
> return traverse(this.root);
> }
> 
> // Post-order traversal
> this.postorder = function() {
> if (!this.root) return null;
> 
> function traverse(node) {
> if (!node) return [];
> const nodes = traverse(node.left); // Left
> nodes.push(...traverse(node.right)); // Right
> nodes.push(node.value); // Root (post-order)
> return nodes;
> }
> 
> return traverse(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-depth-first-search-in-a-binary-search-tree/301719/2 "2025-01-08T15:51:11Z")

</div>

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


