I'm trying to create a tree using a list or an array implementation of incoming integers. They need to be added to the tree as they're entered. The code below is what I have so far, but after around the 5th number entered, some of the previous elements are being overwritten. I'm unsure of how to correct this problem. I'm brand new to Python but have background knowledge in Java. I'm trying to learn how different data structures are implemented in other languages.
EDIT: Some sample input would be 6,8,3,9,2,1. They would be entered separately until a sentinel value was entered (in this case 'end'). The '$' are there to represent an empty element so if 6 was entered first, that would be the root. Then 8 would be its right child. If no numbers less than 6 were entered, the root's left child would be "$". Once the tree is printed using the above values, it should reflect the attached picture. Expected Output
binaryTree = ["$","$"];
counter = 0;
def update(user_input):
if(binaryTree[0] == "$"): # set root
binaryTree[0] = user_input;
binaryTree.append("$");
counter += 1;
elif(binaryTree[counter] == "$"): # if current element is empty
if(user_input >= binaryTree[counter-1]): # setting rightChild
binaryTree.append("$");
rightChild = ((counter - 1)*2)+2;
binaryTree[rightChild] = user_input
elif(user_input < binaryTree[counter -1]): # setting leftChild
binaryTree.append("$");
leftChild = ((counter-1)*2)+1;
binaryTree[leftChild] = user_input;
binaryTree.append("$");
counter += 1;
else: # if current element is NOT empty
if(user_input >= binaryTree[counter-2]):
binaryTree.append("$");
rightChild =((counter-2)*2)+2;
binaryTree[rightChild] = user_input;
elif(user_input < binaryTree[counter -2]):
binaryTree.append("$");
leftChild = ((counter-2)*2)+1;
binaryTree[leftChild] = user_input;
counter += 1;