Pregunta 3 · Programació II UDL 2022
Tema: Árboles binarios y heaps · Del examen Examen Segundo Parcial Enero 2022 (2022)
Enunciado
Pregunta 3 (3,5 puntos). Método leavesMinusInternal para árbol binario
Escribe la implementación de un método en Java llamado leavesMinusInternal que tome por parámetro un árbol de tipo BinaryTree<Integer> y devuelva la diferencia resultante de restar la suma de los nodos interiores a la suma de los nodos hoja:
En el caso particular de que el árbol esté vacío, la función debe retornar 0.
En la Figura 3 se ilustran dos ejemplos de ejecución:
Interfaz proporcionada:
public interface BinaryTree<E> extends Collection<E> {
BinaryTree<E> left();
BinaryTree<E> right();
E root();
void removeLeft();
void removeRight();
int height();
Iterator<E> iterator();
BinaryTreeIterator<E> iteratorPre();
BinaryTreeIterator<E> iteratorIn();
BinaryTreeIterator<E> iteratorPost();
BinaryTreeIterator<E> iteratorLevels();
void clear();
boolean contains(Object o);
boolean containsAll(Collection<?> c);
boolean equals(Object o);
int size();
Object[] toArray();
boolean isEmpty();
}
public static int leavesMinusInternal(BinaryTree<Integer> tree)

Solución
Según los criterios oficiales de corrección
Escribe la implementación de un método en Java llamado leavesMinusInternal que tome por parámetro un árbol de tipo BinaryTree<Integer> y devuelva la diferencia resultante de restar la suma de los nodos interiores a la suma de los nodos hoja.
Solución: ```java public static int leavesMinusInternal(BinaryTree<Integer> tree) { if (tree == null || tree.isEmpty()) { return 0; } boolean hasLeft = tree.left() != null && !tree.left().isEmpty(); boolean hasRight = tree.right() != null && !tree.right().isEmpty(); // Si es una hoja (no tiene descendientes ni por la izquierda ni por la derecha) if (!hasLeft && !hasRight) { return tree.root(); } // Si es un nodo interior, resta su valor y suma el resultado de sus ramas int leftContribution = hasLeft ? leavesMinusInternal(tree.left()) : 0; int rightContribution = hasRight ? leavesMinusInternal(tree.right()) : 0; return leftContribution + rightContribution - tree.root(); } ```
La explicación paso a paso, hecha con IA, es Premium. Premium
Resuélvelo aquí mismo: corrección automática, pistas y solución paso a paso.