递归调用中的返回语句

Tan*_*rya 1 javascript algorithm recursion binary-search-tree

根据我对递归调用的了解,当您通过调用函数递归到该语句时,该语句必须是一个return语句,因为从根本上说,当它从函数堆栈中弹出时,它希望从较早的调用中获得一些值。

我有一些插入BST的代码

insertCorrectLocation(root, newNode) {
    if (newNode.data < root.data) {
        if (root.left == null) {
            root.left = newNode
        } else {
            return this.insertCorrectLocation(root.left, newNode)
        }
    }
    else {
        if (root.right == null) {
            root.right = newNode
        } else {
            return this.insertCorrectLocation(root.right, newNode)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

即使我删除了调用的return语句(例如,

else {
    if (root.right == null) {
        root.right = newNode
    } else {
        this.insertCorrectLocation(root.right, newNode)
    }
}
Run Code Online (Sandbox Code Playgroud)

这是怎么发生的?

Cer*_*nce 5

在递归函数中,仅return当递归函数的外部使用者需要接收值时,才需要(明确地),例如:

const foundNode = tree.findNode(5);
Run Code Online (Sandbox Code Playgroud)

在这种情况下,由于您只插入一个值,而不检索一个值,因此不需要递归returns。

(如果没有return语句,函数将在到达块末尾时自动返回,并将控制权传递给调用者)