A Complet Guide to Preorder Traversal

What is Preorder Traversal?

Pre-Order traverses the binary tree in which our directions are fixed: root -> left -> right. It means that the root will be traversed first, then the left subtree, and then the right subtree.

Problem Statement

Suppose you are given a binary tree. You need to print the preorder traversal of the tree.

A recursive approach is implemented by first calling the root of the current tree and then traversing the left and right subtrees.

Recursive Approach

Time Complexity: O(N), where N is size of binary tree  Space Complexity: O(1)

How to implement Recursive approach in different programming languages?

Iterative Approach

It uses stack data structure to print the preorder traversal.

Time Complexity: O(N), where N is size of binary tree  Space Complexity: O(N)

How to implement Iterative approach in different programming languages?