Creating a tree with Left | 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 depth first order ; Driver code
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . Next = self . child = None NEW_LINE self . data = data 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 = newNode ( data ) NEW_LINE return n . Next 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 = newNode ( data ) NEW_LINE return n . child NEW_LINE DEDENT DEDENT def traverseTree ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT while ( root ) : NEW_LINE INDENT print ( root . data , end = " ▁ " ) NEW_LINE if ( root . child ) : NEW_LINE INDENT traverseTree ( root . child ) NEW_LINE DEDENT root = root . Next NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 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