剑指offer-3.8-55.1

这篇博客探讨了计算二叉树最大深度的三种不同方法:深度优先搜索(DFS)、广度优先搜索(BFS)和递归。每种方法都有其独特的优势和实现细节,适用于不同的场景。DFS直接计算当前节点的最大深度,BFS则通过层次遍历获取,而递归方法利用了左右子树的最大深度来确定整个树的最大深度。
摘要由CSDN通过智能技术生成

在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int depth = 0, maxDepth = 0;
    public void dfs(TreeNode root) {
        if (root == null) {
            return;
        }
        depth++;
        if (depth > maxDepth) {
            maxDepth = depth;
        }
        dfs(root.left);
        dfs(root.right);
        depth--;
    }
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return depth;
        }
        dfs(root);
        return maxDepth;
    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }
}

层序:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        int res = 0;
        while (!queue.isEmpty()) {
            Queue<TreeNode> temp = new LinkedList<TreeNode>();
            for (TreeNode node : queue) {
                if (node.left != null) {
                    temp.offer(node.left);
                }
                if (node.right != null) {
                    temp.offer(node.right);
                }
            }
            queue = temp;
            res++;
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值