Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root node (selecting some arbitrary node as the root node in the case of a graph) and explores as far as possible along each branch before backtracking. Implement Depth First Search for a given input tree.
To return an array, first we need an empty array, where we can push our node values when we are done traversing them completely.
depthFirstSearchHelper
that takes in an array(solution array that needs to be returned) and the input tree.!tree
) - return from there.array.push()
. This will ensure that the element pushed is a leaf node because we returned right before this traversal.depthFirstSearchHelper(tree.left, arr)
depthFirstSearchHelper(tree.right, arr)
.This is a simple solution and is pretty straightforward. (beauty of recursion).
O(N)
Time, because we are going to visit every node atmost once.