Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

Preorder, inorder & postorder traversal code

class Node:
    def __init__(self, k):
        self.left = None
        self.right = None
        self.key = k


def inorder(root):
    if root != None:
        inorder(root.left)
        print(root.key)
        inorder(root.right)


# Driver Code

root = Node(10)
root.left = Node(20)
root.right = Node(30)
root.right.left = Node(40)
root.right.right = Node(50)

inorder(root)

# time complexity (using recurrence tree method)  - O(n)
where, 
n == total nodes 
# space complexity - O(height of tree)
Note: height can be both n (if each node has exactly 1 child) and 
log(n) (if every node has exactly 2 children).

# IMP NOTE : FOR PREORDER AND POSTORDER JUST ORDER OF STATEMENTS CHANGE

for ex:
below is preorder & postorder traversal with same time & space complexity as inorder

def preorder(root):
    if root == None:
        return
    print(root.key)
    preorder(root.left)
    preorder(root.right)

def postorder(root):
    if root == None:
        return
    preorder(root.left)
    preorder(root.right)
    print(root.key)
    
Source by github.com #
 
PREVIOUS NEXT
Tagged: #inorder #postorder #traversal #code
ADD COMMENT
Topic
Name
3+4 =