LeetCode Hot100:递归穿透值传递问题

题目:104.二叉树的最大深度

1.自底向上依靠return

2.自顶向下依靠全局变量接收

javascript 复制代码
//1.自底向上
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function (root) {
	function dfs(root) {
		if (!root) {
			return 0;
		}
		leftDepth = dfs(root.left);
		rightDepth = dfs(root.right);
		return Math.max(leftDepth, rightDepth) + 1;
	}
	return dfs(root);
};

//自顶向下
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function (root) {
	let depth = 0;
	let ans = 0;
	function dfs(root, depth) {
		if (!root) {
			return;
		}
		depth++;
		ans = Math.max(ans, depth);
		dfs(root.left, depth);
		dfs(root.right, depth);
	}
	dfs(root, depth);
	return ans;
};
相关推荐
im_AMBER19 分钟前
Leetcode 47
数据结构·c++·笔记·学习·算法·leetcode
kyle~29 分钟前
算法数学---差分数组(Difference Array)
java·开发语言·算法
橘颂TA1 小时前
机器人+工业领域=?
算法·机器人
小O的算法实验室2 小时前
2025年TRE SCI1区TOP,随机环境下无人机应急医疗接送与配送的先进混合方法,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
程序员杰哥2 小时前
软件测试之压力测试详解
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·压力测试
小白程序员成长日记2 小时前
2025.11.06 力扣每日一题
算法·leetcode
暴风鱼划水2 小时前
算法题(Python)数组篇 | 4.长度最小的子数组
python·算法·力扣
gugugu.2 小时前
算法:二分算法类型题目总结---(含二分模版)
算法
大G的笔记本2 小时前
算法篇常见面试题清单
java·算法·排序算法
7澄13 小时前
深入解析 LeetCode 数组经典问题:删除每行中的最大值与找出峰值
java·开发语言·算法·leetcode·intellij idea