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]}

--

--

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