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;
};
相关推荐
nm_zfyjt43 分钟前
信息流广告投放优化实践:线索成本评估模型与转化链路重构(家装建材案例)
算法·重构·内蒙古朋友圈广告服务商·内蒙古朋友圈获客
w_zero_one2 小时前
算法--构造
java·数据结构·算法
其实防守也摸鱼3 小时前
信创安全竞赛知识总结与题库
大数据·网络·人工智能·算法·安全·php
小超人诞生日记4 小时前
C++ 智能指针的使用及其原理详解
c++·算法
AiNightVision7 小时前
无人机夜视模块如何选择?——从参数指标到系统集成的完整选型指南
人工智能·算法·计算机视觉·车载系统·无人机·视频·智能硬件
牧羊人.3338 小时前
卷积神经网络之VGG
人工智能·深度学习·神经网络·算法·cnn
小郎君6588 小时前
Vue 多标签页的加载态设计:为什么我没有用 Suspense 实现 PageLoading
vue.js·算法
axe_hu9 小时前
AI产品经理的职业规划与学习路径
人工智能·职场和发展·产品经理·学习方法
JJJennie7779 小时前
MAI Gateway私有化部署全攻略:大模型网关如何接入?附架构图
算法·gateway·ai网关·魔芋ai