By AI Engineering Team

Binary Search Trees - Traversal

Intermediate 4 min
AlgorithmsData StructuresBinary Search Tree

Tree Traversal

Traversal means visiting every node in the tree. There are three main ways to do it, each with different uses.

Three Traversal Methods

  1. In-order: Left → Root → Right
  2. Pre-order: Root → Left → Right
  3. Post-order: Left → Right → Root

The names tell you when you visit the root.

In-Order Traversal

Visit left subtree, then root, then right subtree. For a BST, this gives you values in sorted order.

Start Visit Left Visit Root Visit Right Sorted Order

Implementation

🟨 JavaScript In-Order Traversal
📟 Console Output
Run code to see output...

For the example tree, in-order gives: 20, 30, 40, 50, 60, 70, 80. Sorted!

Pre-Order Traversal

Visit root first, then left, then right. Useful for copying trees or getting prefix expressions.

🟨 JavaScript Pre-Order Traversal
📟 Console Output
Run code to see output...

Post-Order Traversal

Visit left, then right, then root. Useful for deleting trees or getting postfix expressions.

🟨 JavaScript Post-Order Traversal
📟 Console Output
Run code to see output...

Comparison

Order: Left → Root → Right

Result for example tree: 20, 30, 40, 50, 60, 70, 80

Use cases:
• Get sorted values from BST
• Validate BST property
• Print values in order

Iterative Traversal

You can also do traversals with a stack instead of recursion:

🟨 JavaScript Iterative In-Order
📟 Console Output
Run code to see output...

Level-Order Traversal

There’s also level-order (breadth-first), which visits nodes level by level:

🟨 JavaScript Level-Order Traversal
📟 Console Output
Run code to see output...

When to Use Each

  • In-order: When you need sorted values
  • Pre-order: When copying or serializing
  • Post-order: When deleting or calculating
  • Level-order: When you need breadth-first search

Time Complexity

All traversals visit every node once:

  • Time: O(n) where n is number of nodes
  • Space: O(h) where h is height (O(log n) average, O(n) worst)

What’s Next?

You’ve learned all the main BST operations. Let’s test your knowledge with a quiz and some practice problems.

Discussion

Join the conversation and share your thoughts

Discussion

0 / 5000