Categorías
Algorithms

LeetCode – Secuencia consecutiva más larga del árbol binario (Java)

Dado un árbol binario, encuentre la longitud de la ruta de secuencia consecutiva más larga.

La ruta se refiere a cualquier secuencia de nodos desde algún nodo inicial hasta cualquier nodo del árbol a lo largo de las conexiones padre-hijo. La ruta consecutiva más larga debe ser de padre a hijo (no puede ser al revés).

Solución Java 1 – BFS

public int longestConsecutive(TreeNode root) {
    if(root==null)
        return 0;
 
    LinkedList<TreeNode> nodeQueue = new LinkedList<TreeNode>();
    LinkedList<Integer> sizeQueue = new LinkedList<Integer>();
 
    nodeQueue.offer(root);
    sizeQueue.offer(1);
    int max=1;
 
    while(!nodeQueue.isEmpty()){
        TreeNode head = nodeQueue.poll();
        int size = sizeQueue.poll();
 
        if(head.left!=null){
            int leftSize=size;
            if(head.val==head.left.val-1){
                leftSize++;
                max = Math.max(max, leftSize);
            }else{
                leftSize=1;
            }
 
            nodeQueue.offer(head.left);
            sizeQueue.offer(leftSize);
        }
 
        if(head.right!=null){
            int rightSize=size;
            if(head.val==head.right.val-1){
                rightSize++;
                max = Math.max(max, rightSize);
            }else{
                rightSize=1;
            }
 
            nodeQueue.offer(head.right);
            sizeQueue.offer(rightSize);
        }
 
 
    }
 
    return max;
}
  LeetCode: número de submatrices con máximo acotado (Java)

Solución Java 2 – DFS

class Solution {
    int max;
 
    public int longestConsecutive(TreeNode root) {
        helper(root);
        return max;
    }
 
    private int helper(TreeNode t){
        if(t==null){
            return 0;
        }
 
        int leftMax = helper(t.left);
        int rightMax = helper(t.right);
 
        int leftTotal = 0;
        if(t.left == null){
            leftTotal = 1;
        }else if(t.val+1 == t.left.val){
            leftTotal = leftMax+1;    
        }else{
            leftTotal = 1;
        }
 
        int rightTotal = 0;
        if(t.right == null){
            rightTotal = 1;
        }else if(t.val+1 == t.right.val){
            rightTotal = rightMax+1;    
        }else{
            rightTotal = 1;
        }
 
        max = Math.max(max, leftTotal);
        max = Math.max(max, rightTotal);
 
        int longer = Math.max(leftTotal, rightTotal);   
 
        return longer;
    }    
}

Por Programación.Click

Más de 20 años programando en diferentes lenguajes de programación. Apasionado del code clean y el terminar lo que se empieza. ¿Programamos de verdad?

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *