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;
};
相关推荐
All for pursuit.5 分钟前
【动态规划-6】96.不同的二叉搜索树
数据结构·c++·算法·leetcode·动态规划
rou15 分钟前
Attention(注意力机制)
算法
信奥卷王35 分钟前
[GESP202609 六级] 数组划分
数据结构·算法
牧羊人.3331 小时前
动手学深度学习 07|Resnet网络与迁移学习
网络·人工智能·深度学习·神经网络·算法·cnn·迁移学习
All for pursuit.2 小时前
【并查集-2】399.除法求值
数据结构·c++·算法·leetcode
迪丽热爱2 小时前
一、C语言概述与程序结构
c语言·开发语言·算法
码爸2 小时前
动态规划介绍
算法·动态规划
怪奇云呼军3 小时前
教育试听预约后没到课,闪电智能 Voice Agent 如何做分层回访?
人工智能·python·算法·云计算·音视频
Nil2083 小时前
leetcode 416分割等和子集
算法·leetcode·职场和发展
云淡风轻~窗明几净3 小时前
角谷猜想的进展之三 移动了群山/沸騰的群山 2026-10-10
人工智能·算法·dubbo·图论