I have a BST in python, with each node holding 3 pieces of data. Those pieces of data being ID, Mark, and Name.
What I’m trying to do is search for a Name, but the nodes are based on IDs, this is how I’ve searched. The function is supposed to output the ID of the specific Name.
def findName(tree,name):
if tree==None:
return None
elif tree['name']==name:
return tree['id']
if tree['left']!=None:
return findName(tree['left'],name)
if tree['right']!=None:
return findName(tree['right'],name)
Unfortunately I’ll only ever be searching the left side of the Tree, and not the right, the opposite applies if I search the right side first.
How do I search both sides for this?
You shouldn’t
returnif you’re not yet finished! Instead, you can replace your last 4 lines with a single, short-circuitingor:Make sure your IDs don’t include
0, though, otherwise this method will fail because0is a falsy value, just like None.