Spróbuj użyć węzły jako narzędzie do rekonstrukcji najgłębszy ścieżkę
Problem może być o to, że nie masz sposób przechowywania rzeczywistych węzłów, jak przechodzić przez drzewo. Co trzeba to sposób na „pamiętać”, który odwiedzonych węzłów na drodze do liści, które uznają za najgłębszy.
Jeśli BST jest reprezentowana w węzłach, może warto rozważyć przechowywania odwołanie, w każdego dziecka, do jego rodzica. W ten sposób, gdy masz do najgłębszej liści, można rekurencyjnie rekonstruować drogę z powrotem do korzeni (uwaga: ścieżka będzie w odwrotnej kolejności). 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;
}
Istnieją inne sposoby, aby to zrobić, jeśli nie chcesz korzystać z węzłów, ale to jest łatwym sposobem na wizualizację problemu w głowie.