# Define the binary tree node structure class Node: def __init__(self, value): self.data = value self.left = None self.right = None # Preorder traversal function def preorder_recursive(root): if root is not None: # Visit the root node print(root.data, end=" ") # Traverse the left subtree preorder_recursive(root.left) # Traverse the right subtree preorder_recursive(root.right)
# Define the binary tree node structure class Node: def __init__(self, value): self.data = value self.left = None self.right = None # Preorder traversal function def preorder_recursive(root): if root is not None: # Visit the root node print(root.data, end=" ") # Traverse the left subtree preorder_recursive(root.left) # Traverse the right subtree preorder_recursive(root.right)
# Preorder traversal function def preorder_iterative(root): if root is None: return stack = [] stack.append(root) while stack: current_node = stack.pop() print(current_node.data, end=" ") # Push the right child onto the stack first if current_node.right: stack.append(current_node.right) # Push the left child onto the stack next if current_node.left: stack.append(current_node.left)