Algorithm Steps
- Start at the
root
node of the binary tree. - Visit the current node and process its value.
- Recursively traverse the
left
subtree. - Recursively traverse the
right
subtree. - 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)