📕
Dan Fitz's Notes
  • README
  • Ai
    • Supervised Machine Learning
      • Introduction To Machine Learning
      • Regression With Multiple Input Variables
      • Classification
  • Csharp
    • C Sharp Advanced
      • Generics
      • Delegates
      • Lambda Expressions
      • Events
    • C Sharp Fundamentals
      • Intro To C
      • Primitive Types And Expressions
      • Non Primitive Types
      • Control Flow
      • Arrays And Lists
      • Working With Dates
      • Working With Text
      • Working With Files
      • Debugging Applications
    • C Sharp Intermediate
      • Classes
      • Association Between Classes
      • Inheritance
      • Polymorphism
      • Interfaces
  • Java
    • Inheritance Data Structures Java
      • Inheritance Polymorphism Using Overriding And Access Modifiers
      • Abstract Classes And Debugging
      • File I O And Exceptions
      • Collections Maps And Regular Expressions
    • Intro To Java
      • Introduction To Java Classes And Eclipse
      • Unit Testing Arrays And Array Lists
      • Static Variables Methods And Polymorphism Using Overloading
  • Javascript
    • Algorithms Data Structures
      • Big O Notation
      • Analyzing Performance Of Arrays And Objects
      • Problem Solving Approach
      • Problem Solving Patterns
      • Recursion
      • Searching Algorithms
      • Bubble Selection And Insertion Sort
      • Merge Sort
      • Quick Sort
      • Radix Sort
      • Data Structures Introduction
      • Singly Linked Lists
      • Doubly Linked Lists
      • Stacks And Queues
      • Binary Search Trees
      • Tree Traversal
      • Binary Heaps
    • Complete Nodejs
      • Understanding Node.js
      • REST AP Is And Mongoose
      • API Authentication And Security
      • Node.js Module System
      • File System And Command Line Args
      • Debugging Node.js
      • Asynchronous Node.js
      • Web Servers
      • Accessing API From Browser
      • Application Deployment
      • Mongo DB And Promises
    • Complete React Native
      • Working With Content
      • Building Lists
      • Navigating Users Between Screens
      • State Management
      • Handling Screen Layout
      • Setting Up An App
      • More On Navigation
      • Advanced Statement Management With Context
      • Building A Custom Express API
      • In App Authentication
    • Epic React
      • React Fundamentals
      • React Hooks
      • Advanced React Hooks
      • Advanced React Patterns
      • React Performance
    • Fireship Firestore
      • Firestore Queries And Data Modeling Course
      • Model Relational Data In Firestore No SQL
    • Functional Light Javascript
      • Intro
      • Function Purity
      • Argument Adapters
      • Point Free
      • Closure
      • Composition
      • Immutability
      • Recursion
      • List Operations
      • Transduction
      • Data Structure Operations
      • Async
    • Js Weird Parts
      • Execution Contexts And Lexical Environments
      • Types And Operators
      • Objects And Functions
      • Object Oriented Java Script And Prototypal Inheritance
      • Defining Objects
    • Mastering Chrome Dev Tools
      • Introduction
      • Editing
      • Debugging
      • Networking
      • Auditing
      • Node.js Profiling
      • Performance Monitoring
      • Image Performance
      • Memory
    • React Complete Guide
      • What Is React
      • React Basics
      • Rendering Lists And Conditionals
      • Styling React Components
      • Debugging React Apps
      • Component Deep Dive
      • Building A React App
      • Reaching Out To The Web
      • Routing
    • React Testing
      • Intro To Jest Enzyme And TDD
      • Basic Testing
      • Redux Testing
      • Redux Thunk Testing
    • Serverless Bootcamp
      • Introduction
      • Auction Service Setup
      • Auction Service CRUD Operations
      • Auction Service Processing Auctions
    • Testing Javascript
      • Fundamentals Of Testing
      • Static Analysis Testing
      • Mocking Fundamentals
      • Configuring Jest
      • Test React Components With Jest And React Testing Library
    • Typescript Developers Guide
      • Getting Started With Type Script
      • What Is A Type System
      • Type Annotations In Action
      • Annotations With Functions And Objects
      • Mastering Typed Arrays
      • Tuples In Type Script
      • The All Important Interface
      • Building Functionality With Classes
    • Web Performance With Webpack
      • Intro
      • Code Splitting
      • Module Methods Magic Comments
  • Other
    • Algo Expert
      • Defining Data Structures And Complexity Analysis
      • Memory
      • Big O Notation
      • Logarithm
      • Arrays
      • Linked Lists
      • Hash Tables
      • Stacks And Queues
      • Strings
      • Graphs
      • Trees
    • Aws Solutions Architect
      • AWS Fundamentals IAM EC 2
    • Fundamentals Math
      • Numbers And Negative Numbers
      • Factors And Multiples
      • Fractions
    • Mysql Bootcamp
      • Overview And Installation
      • Creating Databases And Tables
      • Inserting Data
      • CRUD Commands
      • The World Of String Functions
      • Refining Our Selections
      • The Magic Of Aggregate Functions
    • Random Notes
      • Understanding React Hooks
  • Python
    • Data Analysis Using Python
      • Loading Querying And Filtering Data Using The Csv Module
      • Loading Querying Joining And Filtering Data Using Pandas
      • Summarizing And Visualizing Data
    • Intro To Python
      • Course Introduction Intro To Programming And The Python Language Variables Conditionals Jupyter Notebook And IDLE
      • Intro To Lists Loops And Functions
      • More With Lists Strings Tuples Sets And Py Charm
      • Dictionaries And Files
Powered by GitBook
On this page
  • Breadth-first Search
  • Depth-first Search
  • Pre-order
  • Post-order
  • In-order
  • When to Use BFS or DFS
  • Breadth vs. depth
  • Uses for variants of DFS
  1. Javascript
  2. Algorithms Data Structures

Tree Traversal

The basic question behind tree traversal is this: given any kind of tree, how do you visit every node once?

With any list (like linked lists or arrays), traversal is simple: go from start to finish or left to right.

There are 2 main approaches to tree traversal:

  1. Breadth-first search: working your way horizontally through each level of the tree (i.e. siblings)

  2. Depth-first search: working your way vertically through each branch of the tree (i.e. parents and children)

Breadth-first Search

Breadth-first search depends on a queue to track what needs to be iterated through, using a while loop to continually dequeue nodes and enqueue their children until the queue is empty.

breadthFirstSearch() {
 const queue = []
 const visited = []

 if (this.root) queue.push(this.root)

 while (queue.length !== 0) {
   // Dequeue
   const node = queue.shift()
   visited.push(node.val)

   // Enqueue children
   if (node.left) queue.push(node.left)
   if (node.right) queue.push(node.right)
 }

 return visited
}

Pro tip: When working with other kinds of trees, the enqueue step is what will differ.

Depth-first Search

The basic idea of depth-first search is to traverse vertically down from the root to a leaf. The only difference is the order in which we visit the nodes.

Pre-order

With pre-order, we

  1. Visit a given node.

  2. Traverse all the way down a node's left node.

  3. Traverse all the way down a node's right node.

// Recursive solution
preorderDFS() {
  const visited = []

  const traverse = node => {
    // 1. Visit
    visited.push(node.val)

    // 2 & 3. Traverse
    if (node.left) traverse(node.left)
    if (node.right) traverse(node.right)
  }

  if (this.root) traverse(this.root)

  return visited
}

//     8
//  3     10
// 2 4   9  14

// Becomes [8, 3, 2, 4, 10, 9, 14]

Because we visit the node first, the end result of pre-order DFS is that all left node children are visited first.

Post-order

With post-order, we

  1. Traverse all the way down a node's left node.

  2. Traverse all the way down a node's right node.

  3. Visit the given node.

postorderDFS() {
  const visited = []

  const traverse = node => {
    // 1 & 2. Traverse
    if (node.left) traverse(node.left)
    if (node.right) traverse(node.right)

    // 3. Visit
    visited.push(node.val)
  }

  if (this.root) traverse(this.root)

  return visited
}

//     8
//  3     10
// 2 4   9  14

// Becomes [2, 4, 3, 9, 14, 10, 8]

Because we traverse down the tree first, the end result of post-order DFS is that all children are visited before parents.

In-order

With in-order, we

  1. Traverse all the way down a node's left node.

  2. Visit the given node.

  3. Traverse all the way down a node's right node.

inorderDFS() {
  const visited = []

  const traverse = node => {
    // 1. Traverse
    if (node.left) traverse(node.left)

    // 2. Visit
    visited.push(node.val)

    // 3. Traverse
    if (node.right) traverse(node.right)
  }

  if (this.root) traverse(this.root)

  return visited
}

//     8
//  3     10
// 2 4   9  14

// Becomes [2, 3, 4, 8, 9, 10, 14]

Because we traverse then visit then traverse, the end result of in-order DFS is that you visit nodes in a zig-zag pattern.

When to Use BFS or DFS

In general, the time complexity of BFS and DFS is the same: you're visiting every node once. The difference comes down to space complexity.

Breadth vs. depth

If you're dealing with a very wide tree with lots of branches that spread very far out, depth-first search is likely better than breadth-first search.

That's because, especially as you reach the leafs of a tree, BFS will have a very long queue, which means higher space complexity. In contrast, DFS has a space complexity proportional to the depth of the tree, which ignores width.

Similarly, breadth-first search can be better for very deep trees because DFS will run into the problem of keeping every parent node in memory as it traverses down the tree.

Pro tip: Trees are more likely to be wide than deep, making it the more common situation to code for.

Uses for variants of DFS

Pre-order DFS is great when you want to export a tree structure in an order that makes it easy to reconstruct: its construction order. (You know the intended root because the root is always the first node visited.)

// If given [8, 3, 2, 4, 10, 9, 14]...

// It's easy to recreate the tree
//     8
//  3     10
// 2 4   9  14

In-order DFS is great for sorted trees like binary search trees because it returns everything in its underlying order.

//     8
//  3     10
// 2 4   9  14

// Becomes [2, 3, 4, 8, 9, 10, 14]
PreviousBinary Search TreesNextBinary Heaps

Last updated 3 years ago