我想演练下面的递归代码来寻找二叉树的深度,但不知道条件语句中是否调用递归调用。
var maxDepth = function (root) {
return maxDepthHandler(root, 1);
};
var maxDepthHandler = function (root, depth) {
if (!root) {
return 0;
}
if (!root.right && !root.left) {
return depth;
}
if (root.right && root.left) {
// are these recursive functions called when checking the condition?
if (
maxDepthHandler(root.right, depth + 1) >
maxDepthHandler(root.left, depth + 1)
) {
return maxDepthHandler(root.right, depth + 1);
} else {
// for my follow up question: is this the first recursive call?
return maxDepthHandler(root.left, depth + 1);
}
} else if (root.right !== null) {
return maxDepthHandler(root.right, depth + 1);
} else {
return maxDepthHandler(root.left, depth + 1);
}
};
给出下面的图,如果递归调用没有被调用
13
/ \
8 37
/ \ / \
6 11 24 42
如果条件语句中的递归调用没有被调用 那是否意味着运行maxDepth(13)会导致 maxDepthHandler(root.left, depth + 1);
要成为第一个递归调用?我认为这是因为在第一次调用时,如果不调用条件中的递归调用,则无法计算条件,因此要运行 else 语句。
在你的具体案例中,它们都被调用了。这意味着,你可能应该捕捉它们的值,以避免重复劳动。
let right = maxDepthHandler(root.right, depth + 1);
let left = maxDepthHandler(root.left, depth + 1);
if (right > left) {
return right;
} else {
return left;
}
or:
let right = maxDepthHandler(root.right, depth + 1);
let left = maxDepthHandler(root.left, depth + 1);
return right > left ? right : left;
or: or:
let right = maxDepthHandler(root.right, depth + 1);
let left = maxDepthHandler(root.left, depth + 1);
return Math.max(left, right);
或: 或:
return Math.max(maxDepthHandler(root.left, depth + 1), maxDepthHandler(root.right, depth + 1));
顺便说一下,因为你处理的是null root
则 0
我认为你的其他条件 root.right
和 root.left
如果你的整个函数变成了null,将自动处理。
if (!root) {
return 0;
}
return Math.max(maxDepthHandler(root.left, depth + 1), maxDepthHandler(root.right, depth + 1));
然而,在某些情况下,条件中的函数调用不会被调用。例如,在这个例子中,如果
if(foo(1) || foo(2)) {
...
}
if(foo(3) && foo(4)) {
...
}
在这个例子中,如果 foo(1)
返回 true
జజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజ ||
经营者将 短路 不屑一顾 foo(2)
. 如果 foo(3)
返回 false
జజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజ &&
操作员会短路,所以 foo(4)
不会被调用。
是的,它们会被调用,因为需要它们的值来确定是否进入if语句体。