I'm learning about some basic computer science concepts. As a demo, I'm creating a script in Python that will perform various functions on a binary tree. I've been able to successfully program most of these functions, except for one specific one.
For a binary tree created from an array of integers, I would like to do a depth first search for an integer, and return the path that was taken through the tree up until that integer was found as an array (with the last number in that array being the number that was being searched for). As soon as the first match for that integer is found, I want to stop traversing the tree.
For example, for an inorder dfs of array [3,2,4,1,4,6,8,5] for integer 4, it should return [1,2,3,4]
For integer 5 it should return [1,2,3,4,4,5] etc.
Here is my code:
class Node:
def __init__(self,value):
self.value=value
self.left=None
self.right=None
def getValue(self):
return self.value
def buildTree(array):
print("building tree....")
root=Node(array[0])
del(array[0])
for a in array:
insert(root,Node(a))
print("building complete")
return root
def insert(root,node):
if root is None:
root = node
else:
if root.value < node.value:
if root.right is None:
root.right = node
else:
insert(root.right, node)
else:
if root.left is None:
root.left = node
else:
insert(root.left, node)
def depthFirstSearch(root,target,results,subSearch):
#0:preorder
#1:inorder
#2:postorder
if root!=None:
if subSearch==0:
results.append(root.getValue())
if root.getValue()==target:
return results
depthFirstSearch(root.left,target,results,subSearch)
if subSearch==1:
results.append(root.getValue())
if root.getValue()==target:
return results
depthFirstSearch(root.right,target,results,subSearch)
if subSearch==2:
results.append(root.getValue())
if root.getValue()==target:
return results
return results
if __name__ == '__main__':
#stuff that gets our arguments
#...
array=[3,2,4,1,4,6,8,5] #we would actually get this as an argument, but using this for example array
target=4 #example target
subSearch=1 #using inorder traversal for this example
root=buildTree(array)
results=[]
results=depthFirstSearch(root,target,results,subSearch)
print(results) #expected:[1,2,3,4]
array,target,subSearch).arraywith a binary tree. YourdepthFirstSearch()function is expecting arootthat is supposedly an instance of the classNode. But in your call todepthFirstSearchyou are passing the first element of an array of integers to it instead. You havedepthFirstSearch(array[0], ...). The first thing you'll need to do is to convert your array to a binary tree consisting ofNodes.