Preorder Traversal

garanews's avatar
Published Aug 10, 2022Updated Oct 26, 2022
Contribute to Docs

Preorder traversal is a depth-first search algorithm for a binary search tree that first traverses the root, then the left subtree, and then the right subtree. Its primary use is to create a copy of the tree.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Discover and design new data structures that follow abstract rule-based systems by building out graphs, hash-maps, and heaps.
    • With Certificate
    • Intermediate.
      7 hours

Algorithm

The preorder algorithm can be described as follows:

Function Preorder(tree)
  return root + Preorder(left-subtree) + Preorder(right-subtree)

Example

For the following binary search tree:

Binary Search Tree Diagram

Preorder traversal provides the nodes in the following order: 4, 2, 1, 3, 6, 5, 7.

All contributors

Contribute to Docs

Learn General on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Discover and design new data structures that follow abstract rule-based systems by building out graphs, hash-maps, and heaps.
    • With Certificate
    • Intermediate.
      7 hours