Pregunta 55-1 de la entrevista de oferta de Sword Finger: La profundidad del árbol binario

Una pregunta muy simple, la respuesta no usa variables globales, mejor

 

 

class Solution {
    int max_dep=0;
    public int maxDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        findDepth(root,1);
        return max_dep;
    }

    public void findDepth(TreeNode root,int cur_dep){
        if(cur_dep > max_dep){
            max_dep = cur_dep;
        }
        if(root.left!=null){
            findDepth(root.left,cur_dep+1);
        }

        if(root.right!=null){
            findDepth(root.right,cur_dep+1);
        }
    }
}

 

responder

public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
    }

 

 

Supongo que te gusta

Origin blog.csdn.net/qq_40473204/article/details/115000349
Recomendado
Clasificación