Preorder traversal is one of the Depth First Traversal methods in a binary tree. The sequence of processing nodes is:
Root → Left → Right
1 / \ 2 3 / \ 4 5 ➤ Preorder Traversal Output: 1 2 4 5 3
In preorder, we:
class Node: def __init__(self, val): self.val = val self.left = None self.right = None def preorder(root): if root: print(root.val, end=" ") # Root preorder(root.left) # Left preorder(root.right) # Right
⚡ Tip: Unlike inorder, preorder does not give sorted output in a BST. It is used to record the structure of a tree.
Instead of recursion, we can use a stack to simulate preorder traversal:
def preorder_iterative(root): if not root: return stack = [root] while stack: node = stack.pop() print(node.val, end=" ") if node.right: stack.append(node.right) if node.left: stack.append(node.left)
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!