Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private Node<E> findLCA(Node<E> root, Node<E> n1, Node<E> n2) {
- //Condições de paragem
- if(root == null)
- return null;
- if(n1.getElement() == root.getElement() || n2.getElement() == root.getElement())
- return root;
- //Obter elemento da esquerda:
- Node<E> left = findLCA(root.left, n1, n2);
- //Obter elemento da direita:
- Node<E> right = findLCA(root.right, n1, n2);
- //Se ambos metodos retornarem um valor diferente de null, então o LCA é a root.
- if(left != null && right != null)
- return root;
- return left != null ? left : right;
- }
- /**
- * Descobre a distância entre dois nodes.
- * @param origin
- * @param destination
- * @return
- */
- private int distanceTo(Node<E> origin, Node<E> destination) {
- //Verificações:
- if(origin == null || destination == null)
- return 0;
- //Calcular comparação:
- int c = destination.getElement().compareTo(origin.getElement());
- //Se elementos forem iguais, retornamos 0:
- if(c == 0)
- return 0;
- //Caso contrário escolhemos a direção:
- return c < 0 ? 1+distanceTo(origin.left, destination) : 1+distanceTo(origin.right, destination);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement