With parent references
If you set up each node so that it has a reference to its parent, you can just find the deepest node and then walk back up from there to the root of the tree by tracing through the parents. That is definitely the easiest thing to do at the expense of having an extra parentNode
reference variable in each node.
# Iterate through parents to trace the path in reverse.
node = deepestNode(tree)
while node.parent != None:
node = node.parent
Without parent references
If you do not have parent references, then you can keep track of the path from the root of the tree to the "current" node as you recurse through the tree. Any time you bottom out, save that path as the "longest path so far" if the path is longer than your previous "longest path so far". Effectively that means making your call stack explicit.
Here's some Python-ish code:
# Public function. Sets up globals and then calls helper.
def deepestPath(tree):
global longestPath, currentPath
# Reset for a new search.
longestPath = []
currentPath = []
_deepestPath(tree.root)
return longestPath
# Helper function that does the real work.
def _deepestPath(node):
global longestPath, currentPath
currentPath.append(node)
# No children, we've bottomed out.
if not node.left and not node.right:
if currentPath.length > longestPath.length:
# Save a copy of the current path.
longestPath = list(currentPath)
# Recurse into children.
else:
if node.left: _deepestPath(node.left)
if node.right: _deepestPath(node.right)
currentPath.pop(node)