Skip to content

(Pre|In|Post)Order Traversal In Binary Tree | Recursive Way | Code Snippet

Tree traversal algorithms are easy. Let’s see the Python implementation of these three types of tree traversal in the recursive way.

Click here to see the iterative implementation of tree traversals.

TreeNode Class

class TreeNode:
    
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

Pre Order Traversal

def preorder_traversal(root):
	
	if root is None:
		return
	
	print(root.val)
	preorder_traversal(root.left)
	preorder_traversal(root.right)

In Order Traversal

def inorder_traversal(root):
	
	if root is None:
		return
	
	preorder_traversal(root.left)
	print(root.val)
	preorder_traversal(root.right)

Post Order Traversal

def postorder_traversal(root):

	if root is None:
		return
	
	preorder_traversal(root.left)
	preorder_traversal(root.right)
	print(root.val)
Published inCode Snippets

Comments are closed.