104. Maximum Depth of Binary Tree(二叉树的最大深度)

本文介绍了三种计算二叉树最大深度的方法:递归、深度优先搜索(DFS)和广度优先搜索(BFS)。递归方法简洁明了,通过比较左右子树的最大深度来确定整棵树的深度。深度优先搜索使用栈结构进行节点遍历,记录最大深度。广度优先搜索则通过层序遍历,逐层增加计数来获取最大深度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

在这里插入图片描述

方法思路

Approach1: recursive

class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        int depth = 0;
        int left_depth = maxDepth(root.left);
        int right_depth = maxDepth(root.right);
        depth = left_depth > right_depth ? left_depth : right_depth;
        return depth + 1;
    }
}

简化版本

class Solution {
    //Runtime: 0 ms, faster than 100.00%
    //Memory Usage: 40.1 MB, less than 5.01%
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;
    }
}

Approach2: DFS

class Solution {
    //Runtime: 3 ms, faster than 5.70%
    //Memory Usage: 39.9 MB, less than 6.34%
    public int maxDepth(TreeNode root) {
    if(root == null) {
        return 0;
    }
    
    Stack<TreeNode> stack = new Stack<>();
    Stack<Integer> value = new Stack<>();
    stack.push(root);
    value.push(1);
    int max = 0;
    while(!stack.isEmpty()) {
        TreeNode node = stack.pop();
        int temp = value.pop();
        max = Math.max(temp, max);
        if(node.left != null) {
            stack.push(node.left);
            value.push(temp+1);
        }
        if(node.right != null) {
            stack.push(node.right);
            value.push(temp+1);
        }
    }
    return max;
}
}

Approach3: BFS
层序遍历

class Solution {
    //Runtime: 1 ms, faster than 17.00%
    //Memory Usage: 39.9 MB, less than 6.34%
    public int maxDepth(TreeNode root) {
    if(root == null) {
        return 0;
    }
    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);
    int count = 0;
    while(!queue.isEmpty()) {
        int size = queue.size();
        while(size-- > 0) {
            TreeNode node = queue.poll();
            if(node.left != null) {
                queue.offer(node.left);
            }
            if(node.right != null) {
                queue.offer(node.right);
            }
        }
        count++;
    }
    return count;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值