导出函数中的 javascript 递归 : not a function

标签 javascript recursion

常年新手问题:如何修复这个“不是函数”错误:

exports.height = (input) => {
    function height(node, height) {
        if (node.left) {
            if (height > maxHeight) {
                maxHeight = height;
            }
            **height(node.left, height+1); // <-- Says "Not a function"**
        }
    }

    var maxHeight = 0;
    height( input, 0 ); // <--- This works fine.

    return maxHeight;
}

说,类型错误:高度不是函数

  at height (BinarySearchTree.js:53:5)

谢谢! 尼尔什

最佳答案

您不小心遮蔽了您的height变量

function height(node, <b>height</b>) {
    if (node.left) {
        if (height > maxHeight) {
            maxHeight = height;
        }
        height(node.left, height+1);
    }
}

var maxHeight = 0;
height( input, <b>0</b> ); // 0 is obviously not a function ^_^

尝试将 height 参数重命名为 h

function height(node, <b>h</b>) {
    if (node.left) {
        if (<b>h</b> > maxHeight) {
            maxHeight = <b>h</b>;
        }
        <b>return</b> height(node.left, <b>h</b>+1); // don't forget your return
    }
}

var maxHeight = 0;
height( input, 0 );

尽管如此,您可能需要重新考虑您的功能

function height (node) {
  if (node === undefined)
    return -1;
  else
    return Math.max(height(node.left), height(node.right)) + 1;
}

关于导出函数中的 javascript 递归 : not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40386864/

相关文章:

c++ - 二叉搜索树插入如何使用递归工作?

c - 堆栈溢出,除非递归下的 printf

java - 递归如何与 Java 8 Stream 一起工作?

javascript - Typescript 找不到在 "paths"设置中定义的模块

javascript - 如何忽略 "Unhandled Promise rejection: Template parse errors: ' :gcse:searchbox' is not a known element"

javascript - Material-UI:TextField:react-addons-css-transition-group 与多行 TextField 中断

复制树结构时出现 java.util.ConcurrentModificationException

javascript - 使用按钮通过 JavaScript 切换文本框的状态

javascript - 从指令访问 Controller 功能

Python 循环内的递归调用。它是如何工作的?