Breadth First and Depth First Search

in JavaScript

Objectives

  • explain what a binary search 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

Binary Search Tree

A binary search tree is a data structure for storing data in a way that is easy and quick to search through later.

Think of linked lists but with children instead of siblings

Trees rule(s)

  • if the head node is null, then adding a new item creates a head node
  • Each node has up to 2 children (left and right)
  • If the new item is < than current node, it goes left. If left is null, insert it there
  • If the new item is > than current node, it goes right. If right is null, insert it there

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

  • when was the algorithm created?
  • what was it used for originally?
  • how does it work?

The logic of depth first search

how do we go about searching?

the flow

start depth first search
    parameters node, isMatch callback
    if node is undefined, return false
    if node is a match, return true
    
    if there is a left node
        recursively go down left branch
    if there is a right node
        recursively go down right branch

    no more children, return false

Your turn

make the tests pass for depth first search

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
        if the node matches, return true
        add the nodes children to the queue

Your turn

make the tests pass for breadth first search

Questions

searching with javascript

By Brooks Patton

searching with javascript

depth first search, and breadth first search algorithms with javascript

  • 1,112