38. 二叉树的深度

题目描述

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

代码实现

public class Solution {
    public int TreeDepth(TreeNode root) {
        return root == null ? 0 : Math.max(TreeDepth(root.left), TreeDepth(root.right)) + 1;
    }
}
计算二叉树的最大深度是算法中一个常见的问题,通常可以通过递归或者迭代的方式实现。下面将分别介绍这两种方法的具体实现。 ### 1. 使用递归的方法 递归是一种直观且简单的方法,其核心思想是:当前节点的深度等于左子树和右子树深度的最大值加上1(当前节点本身的深度)。递归的终止条件是当节点为空时,返回深度0。 以下是基于递归方法的Java代码实现: ```java class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; } } public class BinaryTreeMaxDepth { public int maxDepth(TreeNode root) { if (root == null) { return 0; } int leftDepth = maxDepth(root.left); int rightDepth = maxDepth(root.right); return Math.max(leftDepth, rightDepth) + 1; } public static void main(String[] args) { // 构建二叉树 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); BinaryTreeMaxDepth solution = new BinaryTreeMaxDepth(); int maxDepth = solution.maxDepth(root); System.out.println("二叉树的最大深度为:" + maxDepth); } } ``` ### 2. 使用迭代的方法 与递归方法不同,迭代方法使用队列来模拟递归的过程,通过层级遍历的方式计算最大深度。这种方法可以避免递归可能导致的栈溢出问题。 以下是基于迭代方法的Java代码实现: ```java import java.util.LinkedList; import java.util.Queue; class Solution { public int maxDepth(TreeNode root) { if (root == null) { return 0; } Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); int level = 0; while (!queue.isEmpty()) { int count = queue.size(); level++; while (count > 0) { TreeNode current = queue.poll(); if (current.left != null) { queue.offer(current.left); } if (current.right != null) { queue.offer(current.right); } count--; } } return level; } } ``` ### 方法对比 - **递归方法**:实现简单、代码简洁,但可能在大规模数据的情况下导致栈溢出。 - **迭代方法**:使用队列进行层级遍历,避免了栈溢出的问题,适用于更广泛的数据规模[^1]。 两种方法都能正确计算二叉树的最大深度,选择哪一种取决于具体的应用场景和个人偏好。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值