0% found this document useful (0 votes)
100 views11 pages

Tree Traversal

Tree traversal involves visiting all nodes in a tree. There are three common traversal techniques - inorder, preorder and postorder. Inorder traversal visits left subtree, then root, then right subtree. Preorder visits root, left subtree, then right subtree. Postorder visits left subtree, right subtree, then root. Example Python code demonstrates how to implement each traversal on a sample tree.

Uploaded by

Hunzala Shaukat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
100 views11 pages

Tree Traversal

Tree traversal involves visiting all nodes in a tree. There are three common traversal techniques - inorder, preorder and postorder. Inorder traversal visits left subtree, then root, then right subtree. Preorder visits root, left subtree, then right subtree. Postorder visits left subtree, right subtree, then root. Example Python code demonstrates how to implement each traversal on a sample tree.

Uploaded by

Hunzala Shaukat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Tree Traversal

Traversal is a process to visit all the nodes of a tree and may print their
values too. Because, all nodes are connected via edges (links) we always
start from the root (head) node. That is, we cannot randomly access a node
in a tree. There are three ways which we use to traverse a tree −

 In-order Traversal

 Pre-order Traversal

 Post-order Traversal

In-order Traversal
In this traversal method, the left subtree is visited first, then the root and
later the right sub-tree. We should always remember that every node may
represent a subtree itself.

In the below python program, we use the Node class to create place holders
for the root node as well as the left and right nodes. Then we create a insert
function to add data to the tree. Finally the Inorder traversal logic is
implemented by creating an empty list and adding the left node first
followed by the root or parent node. At last the left node is added to
complete the Inorder traversal. Please note that this process is repeated for
each sub-tree until all the nodes are traversed.

class Node:

def __init__(self, data):

self.left = None

self.right = None

self.data = data

# Insert Node

def insert(self, data):


if self.data:

if data < self.data:

if self.left is None:

self.left = Node(data)

else:

self.left.insert(data)

elif data > self.data:

if self.right is None:

self.right = Node(data)

else:

self.right.insert(data)

else:

self.data = data

# Print the Tree

def PrintTree(self):

if self.left:

self.left.PrintTree()

print( self.data),

if self.right:

self.right.PrintTree()

# Inorder traversal

# Left -> Root -> Right

def inorderTraversal(self, root):

res = []

if root:
res = self.inorderTraversal(root.left)

res.append(root.data)

res = res + self.inorderTraversal(root.right)

return res

root = Node(27)

root.insert(14)

root.insert(35)

root.insert(10)

root.insert(19)

root.insert(31)

root.insert(42)

print(root.inorderTraversal(root))

When the above code is executed, it produces the following result −

[10, 14, 19, 27, 31, 35, 42]

Pre-order Traversal
In this traversal method, the root node is visited first, then the left subtree
and finally the right subtree.

In the below python program, we use the Node class to create place holders
for the root node as well as the left and right nodes. Then we create a insert
function to add data to the tree. Finally the Pre-order traversal logic is
implemented by creating an empty list and adding the root node first
followed by the left node. At last the right node is added to complete the
Pre-order traversal. Please note that this process is repeated for each sub-
tree until all the nodes are traversed.

class Node:

def __init__(self, data):


self.left = None

self.right = None

self.data = data

# Insert Node

def insert(self, data):

if self.data:

if data < self.data:

if self.left is None:

self.left = Node(data)

else:

self.left.insert(data)

elif data > self.data:

if self.right is None:

self.right = Node(data)

else:

self.right.insert(data)

else:

self.data = data

# Print the Tree

def PrintTree(self):

if self.left:

self.left.PrintTree()

print( self.data),

if self.right:
self.right.PrintTree()

# Preorder traversal

# Root -> Left ->Right

def PreorderTraversal(self, root):

res = []

if root:

res.append(root.data)

res = res + self.PreorderTraversal(root.left)

res = res + self.PreorderTraversal(root.right)

return res

root = Node(27)

root.insert(14)

root.insert(35)

root.insert(10)

root.insert(19)

root.insert(31)

root.insert(42)

print(root.PreorderTraversal(root))

When the above code is executed, it produces the following result −

[27, 14, 10, 19, 35, 31, 42]

Post-order Traversal
In this traversal method, the root node is visited last, hence the name. First
we traverse the left subtree, then the right subtree and finally the root
node.
In the below python program, we use the Node class to create place holders
for the root node as well as the left and right nodes. Then we create a insert
function to add data to the tree. Finally the Post-order traversal logic is
implemented by creating an empty list and adding the left node first
followed by the right node. At last the root or parent node is added to
complete the Post-order traversal. Please note that this process is repeated
for each sub-tree until all the nodes are traversed.

class Node:

def __init__(self, data):

self.left = None

self.right = None

self.data = data

# Insert Node

def insert(self, data):

if self.data:

if data < self.data:

if self.left is None:

self.left = Node(data)

else:

self.left.insert(data)

elif data > self.data:

if self.right is None:

self.right = Node(data)

else:

self.right.insert(data)

else:
self.data = data

# Print the Tree

def PrintTree(self):

if self.left:

self.left.PrintTree()

print( self.data),

if self.right:

self.right.PrintTree()

# Postorder traversal

# Left ->Right -> Root

def PostorderTraversal(self, root):

res = []

if root:

res = self.PostorderTraversal(root.left)

res = res + self.PostorderTraversal(root.right)

res.append(root.data)

return res

root = Node(27)

root.insert(14)

root.insert(35)

root.insert(10)

root.insert(19)

root.insert(31)

root.insert(42)
print(root.PostorderTraversal(root))

When the above code is executed, it produces the following result −

[10, 19, 14, 31, 42, 35, 27]

Tree Traversals (Inorder, Preorder and Postorder)


Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only
one logical way to traverse them, trees can be traversed in different ways. Following are
the generally used ways for traversing trees.

Example Tree

Depth First Traversals:


(a) Inorder (Left, Root, Right) : 4 2 5 1 3
(b) Preorder (Root, Left, Right) : 1 2 4 5 3
(c) Postorder (Left, Right, Root) : 4 5 2 3 1
Breadth First or Level Order Traversal : 1 2 3 4 5
Please see this post for Breadth First Traversal.
Inorder Traversal (Practice):
Algorithm Inorder(tree)
1. Traverse the left subtree, i.e., call Inorder(left-subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right-subtree)
Uses of Inorder
In case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing
order. To get nodes of BST in non-increasing order, a variation of Inorder traversal
where Inorder traversal s reversed can be used.
Example: Inorder traversal for the above-given figure is 4 2 5 1 3.

Preorder Traversal (Practice):


Algorithm Preorder(tree)
1. Visit the root.
2. Traverse the left subtree, i.e., call Preorder(left-subtree)
3. Traverse the right subtree, i.e., call Preorder(right-subtree)
Uses of Preorder
Preorder traversal is used to create a copy of the tree. Preorder traversal is also used to
get prefix expression on of an expression tree. Please
seehttp://en.wikipedia.org/wiki/Polish_notation to know why prefix expressions are
useful.
Example: Preorder traversal for the above given figure is 1 2 4 5 3.

Postorder Traversal (Practice):


Algorithm Postorder(tree)
1. Traverse the left subtree, i.e., call Postorder(left-subtree)
2. Traverse the right subtree, i.e., call Postorder(right-subtree)
3. Visit the root.
Uses of Postorder
Postorder traversal is used to delete the tree. Please see the question for deletion of
tree for details. Postorder traversal is also useful to get the postfix expression of an
expression tree. Please see http://en.wikipedia.org/wiki/Reverse_Polish_notation to for
the usage of postfix expression.
Example: Postorder traversal for the above given figure is 4 5 2 3 1.

# Python program to for tree traversals


  
# A class that represents an individual node in a
# Binary Tree
class Node:
    def __init__(self,key):
        self.left = None
        self.right = None
        self.val = key
  
  
# A function to do inorder tree traversal
def printInorder(root):
  
    if root:
  
        # First recur on left child
        printInorder(root.left)
  
        # then print the data of node
        print(root.val),
  
        # now recur on right child
        printInorder(root.right)
  
  
  
# A function to do postorder tree traversal
def printPostorder(root):
  
    if root:
  
        # First recur on left child
        printPostorder(root.left)
  
        # the recur on right child
        printPostorder(root.right)
  
        # now print the data of node
        print(root.val),
  
  
# A function to do preorder tree traversal
def printPreorder(root):
  
    if root:
  
        # First print the data of node
        print(root.val),
  
        # Then recur on left child
        printPreorder(root.left)
  
        # Finally recur on right child
        printPreorder(root.right)
  
  
# Driver code
root = Node(1)
root.left      = Node(2)
root.right     = Node(3)
root.left.left  = Node(4)
root.left.right  = Node(5)
print "Preorder traversal of binary tree is"
printPreorder(root)
  
print "\nInorder traversal of binary tree is"
printInorder(root)
  
print "\nPostorder traversal of binary tree is"
printPostorder(root)

Output:
Preorder traversal of binary tree is
1 2 4 5 3
Inorder traversal of binary tree is
4 2 5 1 3
Postorder traversal of binary tree is
4 5 2 3 1
One more example:

Assignment

https://runestone.academy/runestone/books/published/pythonds/Trees/TreeTraversals.html

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy