Last active
April 27, 2019 23:23
-
-
Save benfluleck/81a8ad9a7fa28631514317ef92150395 to your computer and use it in GitHub Desktop.
Depth First Search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Node(value){ | |
this.value = value | |
this.left = null; | |
this.right = null; | |
} | |
Node.prototype.toString = function() { | |
return this.value; | |
} | |
Node.prototype.depthFirstSearch = function depthFirstSearch(rootNode) { | |
if (rootNode === null) { | |
return; | |
} | |
// Print the data of the node. | |
console.log(rootNode.value); | |
depthFirstSearch(rootNode.left); | |
depthFirstSearch(rootNode.right); | |
} |
Most DFS algorithms use a stack to implement however in our case we are using a recursion.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The depth-first algorithm sticks with one path, following that path down a graph structure until it ends. The depth-first search algorithm allows us to determine whether two nodes, node x and node y, have a path between them. The DFS algorithm does this by looking at all of the children of the starting node, node x, until it reaches node y. It does this by recursively taking the same steps, again and again, in order to determine if such a path between two nodes even exists.
Applications of DFS: