Java LeetCode 111. Profundidad mínima del árbol binario

Dado un árbol binario, encuentre su profundidad mínima.
La profundidad mínima es el número de nodos en la ruta más corta desde el nodo raíz hasta el nodo hoja más cercano.
Nota: Un nodo hoja se refiere a un nodo sin nodos secundarios.

Inserte la descripción de la imagen aquí

Travesía primero en amplitud, procesando los nodos en cada fila uno por uno

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    
    
    public int minDepth(TreeNode root) {
    
    
        if(root==null){
    
    
            return 0;
        }
        int size = 1;

        Queue<TreeNode> que = new LinkedList();
        que.offer(root);
        while(!que.isEmpty()){
    
    
            int ss = que.size();
            for(int i=0;i<ss;i++){
    
    
                TreeNode p = que.poll();

                if(p.left==null&&p.right==null){
    
    
                     return size;
                 }if(p.left!=null){
    
    
                    que.offer(p.left);
                 }if(p.right!=null){
    
    
                    que.offer(p.right);
            }
            }
            size++;
        }
        return size;
    }
}

Supongo que te gusta

Origin blog.csdn.net/sakura_wmh/article/details/110727289
Recomendado
Clasificación