全彩夜视+热成像+AI:夜间搜救无人机多光谱感知系统实战
2026/10/1 4:58:14
104. 二叉树的最大深度
简单
给定一个二叉树root,返回其最大深度。
二叉树的最大深度是指从根节点到最远叶子节点的最长路径上的节点数。
示例 1:
输入:root = [3,9,20,null,null,15,7] 输出:3示例 2:
输入:root = [1,null,2] 输出:2提示:
[0, 104]区间内。-100 <= Node.val <= 100“向左右下属汇报工作:我的高度 = max(左下属高度, 右下属高度) + 1 (我这一层)。”
这是一个典型的后序遍历 (Post-order Traversal)模型:
root == null,说明到了空节点(叶子节点的下一层),深度为0。int l = maxDepth(root.left)int r = maxDepth(root.right)Math.max(l, r) + 1。这个+1代表当前节点本身贡献的一层高度。// 题目:LC 104. Maximum Depth of Binary Tree class Solution { public int maxDepth(TreeNode root) { // 1. 递归终止条件:越过叶子节点,高度归零 if (root == null) { return 0; } // 2. 问左孩子有多高 int lDepth = maxDepth(root.left); // 3. 问右孩子有多高 int rDepth = maxDepth(root.right); // 4. 选高的那个,加上自己这一层,汇报给上级 return Math.max(lDepth, rDepth) + 1; } }Queue。每遍历完一层,depth++。虽然代码长一点,但思路也很直观。如果面试官问“不用递归怎么做”,就写 BFS。树结构:
3 / \ 9 20 / \ 15 7maxDepth(9): 左null(0), 右null(0) ->max(0,0)+1=1。maxDepth(15):max(0,0)+1=1。maxDepth(7):max(0,0)+1=1。maxDepth(20): 左(15返回1), 右(7返回1) ->max(1,1)+1=2。maxDepth(3): 左(9返回1), 右(20返回2) ->max(1,2)+1=3。结果:3。