题目: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;
};