【发布时间】:2021-06-03 18:54:56
【问题描述】:
我目前正在尝试解决这个问题:https://leetcode.com/problems/maximum-depth-of-binary-tree/
这是我的代码:
function TreeNode(val, left, right) {
this.val = (val===undefined ? 0 : val)
this.left = (left===undefined ? null : left)
this.right = (right===undefined ? null : right)
}
const NINE = new TreeNode(9);
const FIFTEEN = new TreeNode(15);
const SEVEN = new TreeNode(7);
const TWENTY = new TreeNode(20, FIFTEEN, SEVEN);
const THREE = new TreeNode(3, NINE, TWENTY);
var maxDepth = function(root) {
let max = 0;
helper(root, max, 0);
console.log(max, 'max')
return max + 1;
};
function helper(root, max, i) {
if(root === null) return max;
if(max < i) {
max = i;
}
const maxLeft = helper(root.left, max, i+1);
const maxRight = helper(root.right, max, i+1);
return max = maxLeft > maxRight ? maxLeft : maxRight;
}
maxDepth(THREE);
至此,我有 3 个问题:
1) 我不明白这一行:
return max = maxLeft > maxRight ? maxLeft : maxRight; //2
这里,maxDepth 函数中的max 值不会也更新吗?在这种情况下,我认为应该是2。但是,当我在原始函数中 console.logged 时,我收到了0 结果。为什么会发生这种情况?如何保留从调用堆栈返回的最大值?
- 最初我在下面写了这两行:
const maxLeft = helper(root.left, max, i+1);
const maxRight = helper(root.right, max, i+1);
作为:
helper(root.left, max, i+1);
helper(root.right, max, i+1);
因为我的逻辑是在这个条件之后:
if(max < i) {
max = i;
}
然而,当函数返回调用堆栈时,max 似乎被设置回 0。为什么 max 的值没有被保留,我们如何保留该值?
- 我仍然对上面的两行感到困惑:
const maxLeft = helper(root.left, max, i+1); //1
const maxRight = helper(root.right, max, i+1); //2
这里,maxLeft 和 maxRight 的值保留为 1 和 2。当我们返回调用堆栈时,为什么不将它们设置回 0?
【问题讨论】:
标签: javascript recursion tree binary-tree callstack