Zkuste použít uzlů jako nástroje k rekonstrukci nejhlubší cestu
Problém možná budete mít, je, že budete mít žádný způsob, jak uložit aktuální uzly, jak si procházet strom. To, co potřebujete, je způsob, jak „pamatovat“, které uzly, které jste navštívili na cestě do listu, který považují za nejhlubší.
Je-li váš BST zastoupena v uzlech, možná budete chtít, aby zvážila uložení odkazu v každé dítě, jeho rodiče. Tímto způsobem, když se dostal do nejhlubšího listu, můžete rekurzivně rekonstruovat cestu zpět do kořenového adresáře (poznámka: Cesta bude v obráceném pořadí). Jako tak:
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;
}
Existují i jiné způsoby, jak dělat to, pokud nechcete používat uzly, ale je to snadný způsob, jak představit problém ve vaší hlavě.