Implementation of tree data structure in Python

Environment: Language used: python Version: 3.3.2 OS: Fedora 20 Data Structure used: Python lists Algorithm: Enter the height of the tree Type “Add” to add a node to the tree: First node should be root For any other value: Ask the user if its a left or a right node Find the possible parents (Note: For example if the height of the tree is 2 with elements 1,2,3. Where 1 is the root node and 2 is left node and 3 is the right node. For node 2 the possible parent is 1 which is at index 1.  ) List the possible parent and allow the user to select the parent Add the value to the node Enter ‘N’ to go to next level or ‘S’ to stay at the same level. (Note: If we take the same example as explained above then the first level is consist of 1 node i.e. root and the 2nd level is consist of child node 2 and 3 and so on) Type “Show” to view the current tree structure Type “exit” to exit the program Code Snippet: Implementing tree data structure using Python Python class buildTree (): """Please run the code with Python 3""" def __init__(self): """Class to build your own tree data structure""" self.root_status=False self.data_list=[] self.current_level=1 def possible_parents(self): result=[] for i in range(self.current_level,self.current_level*2): if self.data_list[i]!=-999: result.append(i) return result def addNode(self,node): """The following function will add the node on the left side of the parent""" val=self.possible_parents() if len(val)==0: print ("Error: No parent available. Cannot add any value as a left node") return else: print ("\n") print ("---List of possible parents:") print ("---Index: " + str([data for data in val])) print ("---Value: " + str([self.data_list[data] for data in val])) print ("---Note: The above list shows the indexes and the values of the possible parents. Select the index for which you want to assign the current node as parent") while True: input_user=int(input(">>")) if input_user not in val: print ("Error: Incorrect input. Try Again") else: break input_value=int(input("---Enter the value for {} node with parent {} >> ".format(node,self.data_list[input_user]))) try: if node=="Left": self.data_list[input_user*2]=input_value elif node=="Right": self.data_list[input_user*2+1]= input_value return except: print ("Error: No more space left. Please try again with a higher level/height value") return def changeLevel(self): #Asking the user if they want to continue on the same level or move to another level print ("---If you want to move to the next level type N or S...

Read More