Breadth First and Depth First Search

in JavaScript

Objectives

  • explain what a tree is
  • explain what depth first search is
  • explain what breadth first search is
  • implement a depth first search
  • implement a breadth first search

But first, a tree

Think of linked lists but with children instead of siblings

In order for a set of nodes and children to be considered a tree it must satisfy some properties:

  • Every node must have exactly one parent,
  • Except for the root node which cannot have a parent.

 

Hierarchical vs Linear datastructure.

What does a tree look like?

Now on to searches

Depth first and breadth first are not the only ones available

But they are given in interviews sometimes

Depth First Search

how do we go about searching?

the flow

DFS
    parameters node, isMatch callback
    if node is a match, return true
    
    if there is a left node
        if DFS(left node, isMatch)
            return true
    if there is a right node
        if DFS(right node, isMatch)
            return true

    no more children, return false

Breadth first search

answer the following question

  • how does breadth first search differ from depth first search?

The logic of breadth first search

how do we go about searching?

the flow

start breadth first search
    parameters root node, isMatch callback
    create a queue
    add the root node to the queue
    start forever loop
        if queue is empty, return false
        get node from queue and remove it from queue
        if the node matches, return true
        add the nodes children to the queue

    return false

Questions

Tree Traversals: DFS and BFS

By Hamid Aghdaee

Tree Traversals: DFS and BFS

depth first search, and breadth first search algorithms with javascript

  • 747