माता पिता संदर्भ के साथ
ताकि वह अपने माता-पिता के लिए एक संदर्भ है आप प्रत्येक नोड सेट करते हैं, तो आप सिर्फ गहरी नोड पा सकते हैं और उसके बाद माता-पिता के माध्यम से पता लगाने के द्वारा पेड़ की जड़ से ऊपर वहाँ से वापस चलते हैं। यह निश्चित रूप से एक अतिरिक्त होने की कीमत पर करने के लिए सबसे आसान काम है parentNodeप्रत्येक नोड में संदर्भ चर।
# Iterate through parents to trace the path in reverse.
node = deepestNode(tree)
while node.parent != None:
node = node.parent
माता-पिता के संदर्भ के बिना
आप माता-पिता के संदर्भ की जरूरत नहीं है, तो आप पथ का ट्रैक पेड़ की जड़ से "वर्तमान" नोड के लिए के रूप में आप पेड़ के माध्यम से recurse रख सकते हैं। किसी भी समय आप बाहर नीचे, "सबसे लंबे समय तक पथ अब तक" के रूप में "अब तक सबसे लंबे समय तक पथ" पथ अपने पिछले से अधिक लंबी है, तो उस पथ को बचाने के। प्रभावी ढंग से है कि आपकी कॉल स्टैक स्पष्ट बनाने का मतलब है।
यहाँ कुछ अजगर-इश कोड है:
# 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)