【发布时间】:2020-10-01 16:38:52
【问题描述】:
我正在尝试遍历以下递归代码以查找二叉树的深度,但不知道是否调用了条件中的递归调用:
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 语句。
【问题讨论】:
标签: algorithm recursion conditional-statements binary-tree depth