import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public int maxDepth (TreeNode root) {
        if(root == null) return 0;
        return Math.max(maxDepth(root.left),maxDepth(root.right)) +1;
    }
}

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public int maxDepth (TreeNode root) {
        int max = dfs(root,0,0);
        return max;
    }

    public int dfs(TreeNode root, int cur, int max){
        if(root == null) return max;
        cur++;
        max = Math.max(cur,max);

        int curnum = 0;
        curnum = cur;

        int a = dfs(root.left,curnum,max);
        int b = dfs(root.right,curnum,max);

        return Math.max(max,Math.max(a,b));

    }
}



简洁代码

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(!root) return 0;  //递归边界
         return max(maxDepth(root->left),maxDepth(root->right))+1;  //计算左子树和右子树深度取大者最后+1 = 树的深度
    }
};