С родительским ссылками
Если настроить каждый узел так , что он имеет ссылку на его родитель, вы можете просто найти самый глубокий узел , а затем идти назад оттуда к корню дерева, прослеживая через родитель. Это, безусловно , проще всего сделать за счет наличия дополнительного parentNodeссылочной переменной в каждом узле.
# Iterate through parents to trace the path in reverse.
node = deepestNode(tree)
while node.parent != None:
node = node.parent
Без родительских ссылок
Если вы не имеете родительские ссылок, то вы можете отслеживать пути от корня дерева к «текущему» узлу, как вы рекурсии через дерево. Каждый раз, когда вы Дно, сохранить этот путь как «самый длинный путь до сих пор», если путь длиннее предыдущей «длинный путь до сих пор». Эффективно это означает, что делает ваш стек вызовов явным.
Вот некоторые Python-МОГ код:
# 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)