Próbáljon ki csomópontok, mint egy eszköz, hogy rekonstruálják a legmélyebb útvonal
A probléma lehet, mivel az, hogy nincs módja annak, hogy tárolja az aktuális csomópont ahogy áthalad a fát. Amire szüksége van egy módja annak, hogy „emlékszik”, amely a csomópontok a felkeresett az utat a levél, amit tartják, hogy a legmélyebb.
Ha a BST képviselteti magát a csomópontokon, akkor érdemes megfontolni, tárolására hivatkozni, minden gyermek, hogy a szülő. Így, ha van, hogy a legmélyebb levél, akkor rekurzívan rekonstruálni az utat vissza a gyökér (Megjegyzés: Az útvonal lesz fordított sorrendben). Így:
if (isDeepest(node)) { // Once you find the deepest node...
return reconstructPath(node); // ...reconstruct the path that took you there.
}
...
// reconstructPath is a method that takes a node (the deepest leaf) as
// an argument and returns an array of the nodes from that node to the root.
private Array reconstructPath(Node node) {
Array deepestPath = new Array();
while(node.parent != node) { // Go up until you reach the root, which will be itself.
deepestPath.add(node); // Add the node to end of the Array
node = node.parent; // Go up one level to the parent of the node
}
deepestPath.reverse(); // reverse the order so it goes root->leaf
return deepestPath;
}
Vannak más módon kell ezt csinálni, ha nem kívánja használni csomópont, de ez egy egyszerű módja, hogy szemléltesse a probléma a fejedben.