Searching A Tree
Searching A Tree
Searching a tree
Depth first search
Start with the root
At any node, if we havent reached our objective, take
the left branch first
When get to a leaf, backtrack to the first decision
point and take the right branch
DFS code
def DFSBinary(root, fcn):
stack= [root]
while len(stack) > 0:
if fcn(stack[0]):
return True
else:
temp = stack.pop(0)
if temp.getRightBranch():
stack.insert(0,
temp.getRightBranch())
if temp.getLeftBranch():
stack.insert(0,
temp.getLeftBranch())
return False
1
5
3, 8
2, 8
1, 4, 8
4, 8
BFS code
Def BFSBinary(root, fcn):
queue = [root]
while len(queue) > 0:
if fcn(queue[0]):
return True
else:
temp = queue.pop(0)
if temp.getLeftBranch():
queue.append(temp.getLeftBranch())
if temp.getRightBranch():
queue.append(temp.getRightBranch())
return False
1
5
4, 6
2, 8
6, 3
8, 1, 4
1, 4, 6
DFS code
def DFSBinaryPath(root, fcn):
stack= [root]
while len(stack) > 0:
if fcn(stack[0]):
return TracePath(stack[0])
else:
temp = stack.pop(0)
if temp.getRightBranch():
stack.insert(0, temp.getRightBranch())
if temp.getLeftBranch():
stack.insert(0, temp.getLeftBranch())
return False
def TracePath(node):
if not node.getParent():
return [node]
else:
return [node] + TracePath(node.getParent())
Ordered search
Suppose we know that the tree is ordered,
meaning that for any node, all the nodes to
the left are less than that nodes value, and
all the nodes to the right are greater than
that nodes value
DFS code
def DFSBinaryOrdered(root, fcn, ltFcn):
stack= [root]
while len(stack) > 0:
if fcn(stack[0]):
return True
elif ltFcn(stack[0]):
temp = stack.pop(0)
if temp.getLeftBranch():
stack.insert(0,
temp.getLeftBranch())
else:
if temp.getRightBranch():
stack.insert(0,
temp.getRightBranch())
return False
5
8
6