Binary Tree ( Array implementation ) | Python3 implementation of tree using array numbering starting from 0 to n - 1. ; create root ; create left son of root ; create right son of root ; Print tree ; Driver Code
tree = [ None ] * 10 NEW_LINE def root ( key ) : NEW_LINE INDENT if tree [ 0 ] != None : NEW_LINE INDENT print ( " Tree ▁ already ▁ had ▁ root " ) NEW_LINE DEDENT else : NEW_LINE INDENT tree [ 0 ] = key NEW_LINE DEDENT DEDENT def set_left ( key , parent ) : NEW_LINE INDENT if tree [ parent ] == None : NEW_LINE INDENT print ( " Can ' t ▁ set ▁ child ▁ at " , ( parent * 2 ) + 1 , " , ▁ no ▁ parent ▁ found " ) NEW_LINE DEDENT else : NEW_LINE INDENT tree [ ( parent * 2 ) + 1 ] = key NEW_LINE DEDENT DEDENT def set_right ( key , parent ) : NEW_LINE INDENT if tree [ parent ] == None : NEW_LINE INDENT print ( " Can ' t ▁ set ▁ child ▁ at " , ( parent * 2 ) + 2 , " , ▁ no ▁ parent ▁ found " ) NEW_LINE DEDENT else : NEW_LINE INDENT tree [ ( parent * 2 ) + 2 ] = key NEW_LINE DEDENT DEDENT def print_tree ( ) : NEW_LINE INDENT for i in range ( 10 ) : NEW_LINE INDENT if tree [ i ] != None : NEW_LINE INDENT print ( tree [ i ] , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - " , end = " " ) NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT root ( ' A ' ) NEW_LINE set_right ( ' C ' , 0 ) NEW_LINE set_left ( ' D ' , 1 ) NEW_LINE set_right ( ' E ' , 1 ) NEW_LINE set_right ( ' F ' , 2 ) NEW_LINE print_tree ( ) NEW_LINE