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;
};
相关推荐
蓝色汪洋2 小时前
xtu oj矩阵
算法
hh随便起个名8 小时前
力扣二叉树的三种遍历
javascript·数据结构·算法·leetcode
写写闲篇儿8 小时前
微软面试之白板做题
面试·职场和发展
Dingdangcat869 小时前
城市交通多目标检测系统:YOLO11-MAN-FasterCGLU算法优化与实战应用_3
算法·目标检测·目标跟踪
tang&10 小时前
滑动窗口:双指针的优雅舞步,征服连续区间问题的利器
数据结构·算法·哈希算法·滑动窗口
拼命鼠鼠10 小时前
【算法】矩阵链乘法的动态规划算法
算法·矩阵·动态规划
LYFlied10 小时前
【每日算法】LeetCode 17. 电话号码的字母组合
前端·算法·leetcode·面试·职场和发展
式51611 小时前
线性代数(八)非齐次方程组的解的结构
线性代数·算法·机器学习
橘颂TA11 小时前
【剑斩OFFER】算法的暴力美学——翻转对
算法·排序算法·结构与算法
叠叠乐11 小时前
robot_state_publisher 参数
java·前端·算法