AlgoMaster Logo

Binary Tree Preorder Traversal

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Recursive Approach

Intuition:

The recursive approach is the most straightforward way to perform a preorder traversal of a binary tree. In a preorder traversal, the root node is visited first, followed by the left subtree, and finally the right subtree. The recursive implementation mimics this order naturally by recursively calling the preorder function for each subtree.

Approach:

  • Visit the root node first.
  • Recursively traverse the left subtree.
  • Recursively traverse the right subtree.

Code:

2. Iterative Approach using Stack

Intuition:

An iterative approach using a stack is a common way to avoid recursion and control the function call behavior explicitly. The idea is to mimic the system's call stack with an explicit stack data structure to store nodes yet to be processed.

Approach:

  • Use a stack to keep track of nodes. Initially, push the root node to the stack.
  • While the stack is not empty, pop a node from the stack, add its value to the result list, and then push its right and left children to the stack (in that order).
  • This ensures that nodes are processed in preorder sequence.

Code:

3. Morris Traversal (Most Optimal)

Intuition:

Morris Traversal modifies the tree structure temporarily to allow traversal of the tree without using additional space or a stack. It uses the concept of threading a binary tree.

Approach:

  1. Start with the root node and initialize the current node to root.
  2. While the current node is not null:
    • If the current node has no left child, add its value to the result and move to its right child.
    • If the current node has a left child, find the rightmost node in the left subtree (inorder predecessor).
    • If the rightmost node's right child is null, set its right child to the current node, and move to the left child.
    • If the rightmost node's right child is the current node (thread already exists), set it back to null (restoring tree structure), add the current node's value to result, and move to its right child.

Code: