Depth First Search (Javascript)

class Node {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
const a = new Node (1)const b = new Node (2)const c = new Node (3)const d = new Node (4)const e = new Node (5)a.left = ba.right = cb.left = db.right = e        1
/ \
2 3
/ \
4 5
const DFS = (root) => {
//make an empty array to house the root
let queue = [root]
//create an empty array to house the visited values
let stack = []
//create a while loop and the logic: "while the stack is greater than 0" while (queue.length > 0) {

//create a variable = to the popped off iteration
let current = queue.pop()
//push the visited value into the stack
stack.push(current.val)
//loop through the left and right if there is a left and right
if (current.left) {
//if there is a left, push it into the stack
queue.push(current.left)
}
if (current.right) {queue.push(current.right)}} return stack
}
const DFS = (root) => {
//create your base case(s)
if (root === null) return [] //create your variables that recursively call the left and right let left = DFS(root.left)
let right = DFS(root.right)

//use the spread operator to return an array of the current //value, the left and the right values
return [root.val, ...left, ..right]}

--

--

--

Flatiron student, word nerd and otter enthusiast

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Clone of Lybrate With Backend

Node.js Server & Authentication Basics: Express, Sessions, Passport, and cURL

Top 5 JavaScript Frameworks For 2021

Why you should buy our NFT??

JavaScript ES6

Theming styled-components with CSS custom properties

Micro Frontends in A Nutshell

Getting Started With Kotlin-React — Part III

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Crystal Villanueva

Crystal Villanueva

Flatiron student, word nerd and otter enthusiast

More from Medium

Everything you need to know about arrays in JavaScript

SOLID Principle & Introduction to JS

Dynamic Programming Tutorial using JavaScript

Linked Lists in Javascript