Binary Tree Preorder Traversal

In this tutorial, i am going to discuss what is binary tree preorder traversal? How to implement binary tree preorder traversal with and without recursion.

Given the root of a binary tree, write a code to return the preorder traversal of its nodes’ values.

Binary tree preorder traversal without recursion

What is preorder traversal?

In preorder traversal –

i) First, we visit the root.

ii) Traverse the left subtree of root in preorder.

iii) Traverse the right subtree of root in preorder.

Binary tree inorder traversal without using recursion

Binary tree level order traversal

Programming video tutorials

Binary Tree Preorder Traversal without Recursion – Java Code

To implement preorder traversal using iterative approach, we are going to use stack data structure. Here are the implementation steps –

i) Declare an stack and push the root node in a stack.

ii) Run a loop while stack is not empty and do the following steps.

a) Pop an item from a stack and add it’s value in a result list.
b) Push the right child of popped item to stack, if it’s not empty.
c) Push the left child of popped item to stack, if it’s not empty.

We have to push the right child before the left child in a stack to make sure that the left subtree is processed first.

The time complexity of this approach is O(n) and its space complexity is also O(n).

Binary Tree Preorder Traversal using Recursion – Java Code

The recursive code is very straightforward. Here is the implementation.

i) Add the node value to a result list.
ii) Recursively call preorderHelper for the left node
iii) Recursively call preorderHelper for the right node

Recursion vs iteration

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.