DFS与回溯专题:二叉树的最大深度
题目链接: 104.二叉树的最大深度
题目描述

代码思路
设置两个变量,max来记录最大值,sum来记录路径的节点数量。利用dfs对二叉树进行搜索,遇到节点,则sum+1;遇到叶子节点,则将max与sum进行比较,取最大值
代码纯享版
class Solution {
    public int max = 0;
    
    public int maxDepth(TreeNode root) {
        int sum = 0;
        dfs(root, sum);
        return max;
    }
    void dfs(TreeNode root, int sum){
        if(root == null) return;
        sum ++;
        if(root.left == null || root.right == null){
            max = Math.max(max, sum);
        }
        dfs(root.left, sum);
        dfs(root.right, sum);
    }
}
代码逐行解析版
class Solution {
    public int max = 0; //最长路径上的节点数
    
    public int maxDepth(TreeNode root) {
        int sum = 0; //统计路径上的节点数
        dfs(root, sum);
        return max;
    }
    void dfs(TreeNode root, int sum){
        if(root == null) return; //节点为空,直接返回
        sum ++; //节点不为空,路径上的节点数加一
        if(root.left == null || root.right == null){ //已经是叶子节点
            max = Math.max(max, sum); //记录最大值
        }
        //对该节点的左右子节点进行搜索
        dfs(root.left, sum);
        dfs(root.right, sum);
    }
}



















