Почему моя функция «Наименьший общий предок» продолжает возвращать ноль, когда я пытаюсь выполнить поиск в моем двоичномJAVA

Программисты JAVA общаются здесь
Ответить
Гость
 Почему моя функция «Наименьший общий предок» продолжает возвращать ноль, когда я пытаюсь выполнить поиск в моем двоичном

Сообщение Гость »

Код: Выделить всё

public String LCA(String s, String t) throws IllegalArgumentException {
// Check if s or t are null or not in the tree
if (s == null || t == null || !stringsToNodes.containsKey(s) || !stringsToNodes.containsKey(t)) {
throw new IllegalArgumentException("s or t are null or not in the tree");
}

// Find nodes containing s and t
Node nodeS = stringsToNodes.get(s);
Node nodeT = stringsToNodes.get(t);

// Get paths from nodes to the root
ArrayStack pathS = getPathToRoot(nodeS);
ArrayStack pathT = getPathToRoot(nodeT);

// Find the intersection of paths
Node lca = findIntersection(pathS, pathT);

// Return the value of the LCA or null if not found
return lca != null ? lca.s : null;
}

// method to find the path from a node to the root
private ArrayStack getPathToRoot(Node node) {
ArrayStack path = new ArrayStack();
while (node != null) {
path.add(node);
node = node.parent;
}
return path;
}

// method to find the intersection of two paths
private Node findIntersection(ArrayStack pathS, ArrayStack pathT) {
Node intersect = null;

// Iterate over both paths until one of them is exhausted
while (!pathS.isEmpty() && !pathT.isEmpty()) {
Node nodeS = pathS.get(pathS.size() - 1);
Node nodeT = pathT.get(pathT.size() - 1);
if (nodeS == nodeT) {
intersect = nodeS;
} else {
break;
}
pathS.remove(pathS.size() - 1); // Move to the previous node in pathS
pathT.remove(pathT.size() - 1); // Move to the previous node in pathT
}

return intersect;
}
Это моя функция
Я пробовал сделать это без частных методов, но мне не удалось найти других решений в Интернете.

Источник: https://stackoverflow.com/questions/781 ... n-i-try-to
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»