Creating a tree with Left | Python3 program to create a tree with left child right sibling representation ; Creating new Node ; Adds a sibling to a list with starting with n ; Add child Node to a Node ; Check if child list is not empty ; Traverses tree in level order ; Corner cases ; Create a queue and enque root ; Take out an item from the queue ; Print next level of taken out item and enque next level 's children ; Driver code
from collections import deque NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . next = None NEW_LINE self . child = None NEW_LINE DEDENT DEDENT def addSibling ( n , data ) : NEW_LINE INDENT if ( n == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT while ( n . next ) : NEW_LINE INDENT n = n . next NEW_LINE DEDENT n . next = Node ( data ) NEW_LINE return n NEW_LINE DEDENT def addChild ( n , data ) : NEW_LINE INDENT if ( n == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT if ( n . child ) : NEW_LINE INDENT return addSibling ( n . child , data ) NEW_LINE DEDENT else : NEW_LINE INDENT n . child = Node ( data ) NEW_LINE return n NEW_LINE DEDENT DEDENT def traverseTree ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT print ( root . data , end = " ▁ " ) NEW_LINE if ( root . child == None ) : NEW_LINE INDENT return NEW_LINE DEDENT q = deque ( ) NEW_LINE curr = root . child NEW_LINE q . append ( curr ) NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT curr = q . popleft ( ) NEW_LINE while ( curr != None ) : NEW_LINE INDENT print ( curr . data , end = " ▁ " ) NEW_LINE if ( curr . child != None ) : NEW_LINE INDENT q . append ( curr . child ) NEW_LINE DEDENT curr = curr . next NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( 10 ) NEW_LINE n1 = addChild ( root , 2 ) NEW_LINE n2 = addChild ( root , 3 ) NEW_LINE n3 = addChild ( root , 4 ) NEW_LINE n4 = addChild ( n3 , 6 ) NEW_LINE n5 = addChild ( root , 5 ) NEW_LINE n6 = addChild ( n5 , 7 ) NEW_LINE n7 = addChild ( n5 , 8 ) NEW_LINE n8 = addChild ( n5 , 9 ) NEW_LINE traverseTree ( root ) NEW_LINE DEDENT