Preorder Traversal of a Binary Tree using Recursion

Preorder Traversal of a Binary Tree using Recursion

Visualization

Algorithm Steps

  1. Start at the root node of the binary tree.
  2. Visit the current node and process its value.
  3. Recursively traverse the left subtree.
  4. Recursively traverse the right subtree.
  5. If the current node is null, return.

Preorder Traversal Program in Different Programming Languages Code

Python
Java
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def preorder(root):
    if root:
        print(root.data, end=' ')
        preorder(root.left)
        preorder(root.right)

# Example usage
if __name__ == '__main__':
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
    print('Preorder traversal:')
    preorder(root)