DFS in JavaScript (Data Structures)

Nilesh Saini
2 min readMay 8, 2022

Short and Precise Js code to do Depth-first Search in a BST

Note: Read about Binary Search Tree and BFS in BST here.

Photo by Marten Newhall on Unsplash

Node:

Preorder Traversal Pseudocode:

  1. Create a variable array to store the values of the nodes visited.
  2. Write a helper function which accepts a node.
  • Push the value of the nod to the variable that stores the values.
  • If the node has the left property, call the helper function with the left property on the node.
  • If the node has the right property, call the helper function with the right property on the node.

3. Return the variable array.

Note:

The helper function can also be written like this:

// helper function
let helper = node => {
if(!root) return;
data.push(node.val);
node.left && helper(node.left);
node.right && helper(node.right);
}

Postorder Traversal Pseudocode:

  1. Create a variable array to store all the values of the nodes visited.
  2. Write a helper function which accepts the node and
  • If the node has a left property, call the helper function with the left property on the node.
  • If the node has the right property, call the helper function with the right property on the node.
  • Push the value of the node to the variable array that stores the values.

3. Invoke the helper function with the root.

4. Return the data array.

Note:

The helper function can also be written like this:

// helper function
let helper = node => {
if(!root) return;
node.left && helper(node.left);
node.right && helper(node.right);
data.push(node.val);
}

Inorder Traversal Pseudocode:

  1. Create a variable array to store all the values of the nodes visited.
  2. Write a helper function which accepts the node and
  • If the node has a left property, call the helper function with the left property on the node.
  • Push the value of the node to the variable array that stores the values.
  • If the node has the right property, call the helper function with the right property on the node.

3. Invoke the helper function with the root.

4. Return the data array.

Note:

The helper function can also be written like this:

// helper function
let helper = node => {
if(!root) return;
node.left && helper(node.left);
data.push(node.val);
node.right && helper(node.right);
}

--

--

Nilesh Saini

Web Developer/ Front-end engineer who loves solving Rubik's Cube