进行一次深度优先搜索,cur表示当前的层数。搜索到的最深的层就是二叉树的最大深度
c++

class Solution {
public:
    int ans = 0;
    void dfs(TreeNode* root,int cur)
    {
        ans = max(ans,cur);
        if(root->left != NULL){ dfs(root->left,cur+1); }
        if(root->right != NULL){ dfs(root->right,cur+1); }
    }
    int maxDepth(TreeNode* root) {
        if(root == NULL){return 0;}
        dfs(root,1);
        return ans;
    }
};

java

import java.util.*;
public class Solution {
    public int maxDepth (TreeNode root) {
        if(root == null){return 0;}
            dfs(root,1);
            return ans;
    }
        int ans = 0;
        public void dfs(TreeNode root,int cur)
        {
            if(ans < cur)ans = cur;
            if(root.left != null){ dfs(root.left,cur+1); }
            if(root.right != null){ dfs(root.right,cur+1); }
        }
}

maxDepth(TreeNode* root) 表示以root为根节点的二叉树的最大深度,等于max(左子树的深度,右子树的深度)+1。
c++

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root == NULL){return 0;}
        return max(maxDepth(root->left),maxDepth(root->right))+1;
    }
};

java

import java.util.*;
import java.lang.Math;
public class Solution {
    public int maxDepth (TreeNode root) {
        if(root == null){return 0;}
        return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
    }
}

python


python