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;
};
相关推荐
自信的小螺丝钉10 分钟前
Leetcode 146. LRU 缓存 哈希表 + 双向链表
leetcode·缓存·散列表
机器学习之心1 小时前
多目标鲸鱼优化算法(NSWOA),含46种测试函数和9个评价指标,MATLAB实现
算法·matlab·多目标鲸鱼优化算法·46种测试函数·9个评价指标
max5006002 小时前
基于Meta Llama的二语习得学习者行为预测计算模型
人工智能·算法·机器学习·分类·数据挖掘·llama
王哥儿聊AI3 小时前
Lynx:新一代个性化视频生成模型,单图即可生成视频,重新定义身份一致性与视觉质量
人工智能·算法·安全·机器学习·音视频·软件工程
手握风云-5 小时前
优选算法的寻踪契合:字符串专题
算法
闭着眼睛学算法5 小时前
【华为OD机考正在更新】2025年双机位A卷真题【完全原创题解 | 详细考点分类 | 不断更新题目 | 六种主流语言Py+Java+Cpp+C+Js+Go】
java·c语言·javascript·c++·python·算法·华为od
IT古董5 小时前
【第五章:计算机视觉-项目实战之目标检测实战】2.目标检测实战:中国交通标志检测-(2)中国交通标志检测数据格式转化与读取
算法·目标检测·计算机视觉
MobotStone5 小时前
LLM 采样入门到进阶:理解与实践 Top-K、Top-P、温度控制
算法
杨小码不BUG6 小时前
CSP-J/S初赛知识点精讲-图论
c++·算法·图论··编码·csp-j/s初赛
测试老哥6 小时前
Python+selenium自动化生成测试报告
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例