親参照あり
親への参照を持つように各ノードを設定すると、最も深いノードを見つけて、そこから親をたどってツリーのルートに戻ることができます。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)