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;
};
相关推荐
快去睡觉~1 小时前
力扣400:第N位数字
数据结构·算法·leetcode
qqxhb2 小时前
零基础数据结构与算法——第七章:算法实践与工程应用-搜索引擎
算法·搜索引擎·tf-idf·倒排索引·pagerank·算法库
汤永红3 小时前
week1-[循环嵌套]画正方形
数据结构·c++·算法
pusue_the_sun3 小时前
数据结构——顺序表&&单链表oj详解
c语言·数据结构·算法·链表·顺序表
yi.Ist4 小时前
图论——Djikstra最短路
数据结构·学习·算法·图论·好难
数据爬坡ing4 小时前
过程设计工具深度解析-软件工程之详细设计(补充篇)
大数据·数据结构·算法·apache·软件工程·软件构建·设计语言
茜子.Java4 小时前
二分算法(模板)
算法
qq_513970446 小时前
力扣 hot100 Day74
数据结构·算法·leetcode
Cx330❀7 小时前
【数据结构初阶】--排序(三):冒泡排序、快速排序
c语言·数据结构·经验分享·算法·排序算法