算法题 二叉树的最大深度

二叉树最大深度算法解析

LeetCode 104. 二叉树的最大深度

问题描述

给定一个二叉树的根节点 root,返回其最大深度

二叉树的深度:从根节点到最远叶子节点的最长路径上的节点数。

叶子节点:没有子节点的节点。

示例

输入: root = [3,9,20,null,null,15,7]
输出: 3
解释: 
    3
   / \
  9  20
    /  \
   15   7
最长路径:3 → 20 → 15(或3 → 20 → 7),共3个节点

输入: root = [1,null,2]
输出: 2

算法思路

方法一:递归法(DFS)

  • 核心思想:树的最大深度 = max(左子树最大深度, 右子树最大深度) + 1
  • 递归终止条件:节点为空时深度为0
  • 递归过程:分别计算左右子树深度,取最大值加1

方法二:迭代法(BFS - 层序遍历)

  • 核心思想:按层遍历,每遍历一层深度加1
  • 实现方式:使用队列存储每层的节点
  • 终止条件:队列为空时返回深度

方法三:迭代法(DFS - 显式栈)

  • 核心思想:模拟递归过程,使用栈存储节点和对应深度
  • 实现方式:栈中存储节点和当前深度的配对
  • 更新最大深度:每次访问节点时更新全局最大深度

代码实现

方法一:递归法(DFS)

/**
 * 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 {
    /**
     * 计算二叉树的最大深度 - 递归实现(DFS)
     * 
     * @param root 二叉树根节点
     * @return 二叉树的最大深度
     */
    public int maxDepth(TreeNode root) {
        // 递归终止条件:空节点深度为0
        if (root == null) {
            return 0;
        }
        
        // 递归计算左右子树的最大深度
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);
        
        // 当前节点的最大深度 = max(左子树深度, 右子树深度) + 1
        return Math.max(leftDepth, rightDepth) + 1;
    }
}

方法二:迭代法(BFS - 层序遍历)

import java.util.LinkedList;
import java.util.Queue;

class Solution {
    /**
     * 计算二叉树的最大深度 - 迭代实现(BFS层序遍历)
     * 
     * @param root 二叉树根节点
     * @return 二叉树的最大深度
     */
    public int maxDepth(TreeNode root) {
        // 空树深度为0
        if (root == null) {
            return 0;
        }
        
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int depth = 0;
        
        // BFS层序遍历
        while (!queue.isEmpty()) {
            depth++; // 每处理一层,深度加1
            int levelSize = queue.size(); // 当前层的节点数
            
            // 处理当前层的所有节点
            for (int i = 0; i < levelSize; i++) {
                TreeNode node = queue.poll();
                
                // 将下一层的节点加入队列
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
        }
        
        return depth;
    }
}

方法三:迭代法(DFS - 显式栈)

import java.util.Stack;

class Solution {
    /**
     * 计算二叉树的最大深度 - 迭代实现(DFS显式栈)
     * 
     * @param root 二叉树根节点
     * @return 二叉树的最大深度
     */
    public int maxDepth(TreeNode root) {
        // 空树深度为0
        if (root == null) {
            return 0;
        }
        
        // 栈中存储节点和对应深度的配对
        Stack<TreeNode> nodeStack = new Stack<>();
        Stack<Integer> depthStack = new Stack<>();
        
        nodeStack.push(root);
        depthStack.push(1);
        
        int maxDepth = 0;
        
        while (!nodeStack.isEmpty()) {
            TreeNode node = nodeStack.pop();
            int currentDepth = depthStack.pop();
            
            // 更新最大深度
            maxDepth = Math.max(maxDepth, currentDepth);
            
            // 将子节点和对应深度压入栈
            if (node.left != null) {
                nodeStack.push(node.left);
                depthStack.push(currentDepth + 1);
            }
            if (node.right != null) {
                nodeStack.push(node.right);
                depthStack.push(currentDepth + 1);
            }
        }
        
        return maxDepth;
    }
}

算法分析

  • 时间复杂度:O(n)
    • 所有方法都需要访问每个节点恰好一次
  • 空间复杂度
    • 递归法:O(h),h为树的高度(最坏O(n),最好O(log n))
    • BFS迭代法:O(w),w为树的最大宽度(最坏O(n))
    • DFS迭代法:O(h),栈空间与树高度相关
  • 方法对比
    • 递归法:代码最简洁,逻辑清晰
    • BFS法:直观地按层计算深度,空间使用与宽度相关
    • DFS迭代法:避免递归栈溢出,空间使用与高度相关

算法过程

输入:root = [3,9,20,null,null,15,7]

    3
   / \
  9  20
    /  \
   15   7

递归法

  1. maxDepth(3)max(maxDepth(9), maxDepth(20)) + 1
  2. maxDepth(9)max(0, 0) + 1 = 1
  3. maxDepth(20)max(maxDepth(15), maxDepth(7)) + 1
  4. maxDepth(15)1, maxDepth(7)1
  5. maxDepth(20)max(1, 1) + 1 = 2
  6. maxDepth(3)max(1, 2) + 1 = 3

BFS

  • 第1层:队列=[3] → depth=1 → 处理后队列=[9,20]
  • 第2层:队列=[9,20] → depth=2 → 处理后队列=[15,7]
  • 第3层:队列=[15,7] → depth=3 → 处理后队列=[]
  • 返回 depth=3

测试用例

public class MaxDepthTest {
    static 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;
        }
    }
    
    // 创建测试树
    static TreeNode createTree1() {
        // [3,9,20,null,null,15,7]
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);
        return root;
    }
    
    static TreeNode createTree2() {
        // [1,null,2]
        TreeNode root = new TreeNode(1);
        root.right = new TreeNode(2);
        return root;
    }
    
    static TreeNode createTree3() {
        // 完全二叉树 [1,2,3,4,5,6,7]
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(7);
        return root;
    }
    
    static TreeNode createTree4() {
        // 链表状树 [1,2,null,3,null,4]
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.left.left = new TreeNode(3);
        root.left.left.left = new TreeNode(4);
        return root;
    }
    
    public static void main(String[] args) {
        Solution solution = new Solution();
        
        // 测试用例1:标准示例
        TreeNode root1 = createTree1();
        System.out.println("Test 1: " + solution.maxDepth(root1)); // 3
        
        // 测试用例2:只有右子树
        TreeNode root2 = createTree2();
        System.out.println("Test 2: " + solution.maxDepth(root2)); // 2
        
        // 测试用例3:空树
        System.out.println("Test 3: " + solution.maxDepth(null)); // 0
        
        // 测试用例4:单节点
        TreeNode root4 = new TreeNode(1);
        System.out.println("Test 4: " + solution.maxDepth(root4)); // 1
        
        // 测试用例5:完全二叉树
        TreeNode root5 = createTree3();
        System.out.println("Test 5: " + solution.maxDepth(root5)); // 3
        
        // 测试用例6:链表状树(最坏情况)
        TreeNode root6 = createTree4();
        System.out.println("Test 6: " + solution.maxDepth(root6)); // 4
        
        // 测试用例7:只有左子树
        TreeNode root7 = new TreeNode(1);
        root7.left = new TreeNode(2);
        root7.left.left = new TreeNode(3);
        System.out.println("Test 7: " + solution.maxDepth(root7)); // 3
        
        // 测试用例8:平衡树
        TreeNode root8 = new TreeNode(1);
        root8.left = new TreeNode(2);
        root8.right = new TreeNode(3);
        root8.left.left = new TreeNode(4);
        System.out.println("Test 8: " + solution.maxDepth(root8)); // 3
    }
}

关键点

  1. 深度定义

    • 节点数计算(不是边数)
    • 空树深度为0,单节点深度为1
  2. 递归核心

    • 分治思想:大问题分解为子问题
    • 基础情况:空节点返回0
    • 递归关系:max(left, right) + 1
  3. BFS vs DFS

    • BFS按层遍历,天然适合计算深度
    • DFS需要额外记录当前深度
  4. 空间复杂度分析

    • 递归法受树高度影响
    • BFS受树宽度影响
    • 对于完全二叉树,BFS空间开销更大

常见问题

  1. 深度和高度有什么区别?

    • 深度:从根到节点的路径长度(根深度为0或1)
    • 高度:从节点到最远叶子的路径长度(叶子高度为0或1)
  2. 为什么递归法的空间复杂度是O(h)?

    • 递归调用栈的深度等于树的高度
    • 完全平衡树:O(log n),退化为链表:O(n)
  3. BFS方法为什么需要记录每层节点数?

    • 队列中可能同时包含多层节点
    • 通过levelSize = queue.size()确保一次只处理一层
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值