【问题标题】:Understanding "return" when it comes to recursion理解递归时的“返回”
【发布时间】:2020-08-27 20:52:05
【问题描述】:

如果您认为问题很重要,那么目标就差不多了。如果相同深度不同的父母返回 true 否则返回 false;

一种情况:输入:root = [1,2,3,4], x = 4, y = 3 输出:假

示例 1:

var isCousins = function(root, x, y) {
    
    const xInfo = getInfo(root, x, null, 0);
    const yInfo = getInfo(root, y, null, 0);
    
    if(xInfo.parent !== yInfo.parent && xInfo.depth === yInfo.depth) return true;
    return false;
};

const getInfo = (root, x , parent, depth) => {
    
    const obj = {
        "parent": parent,
        "depth": depth
    };
    
    if(!root) return;
    if(root.val === x) return obj;
    
    else {
        parent = root.val;
        let left =  getInfo(root.left, x, parent, depth+1);
        if(left) return left;
        let right = getInfo(root.right, x, parent, depth+1);
        if(right) return right;
    }
    
}

示例 2:

var isCousins = function(root, x, y) {
    
    const xInfo = getInfo(root, x, null, 0);
    //const yInfo = getInfo(root, y, null, 0);
    
    if(xInfo.parent !== yInfo.parent && xInfo.depth === yInfo.depth) return true;
    return false;
};

const getInfo = (root, x , parent, depth) => {
    
    const obj = {
        "parent": parent,
        "depth": depth
    };
    console.log(obj)
    
    if(!root) return;
    if(root.val === x) return obj;
    
    else {
        parent = root.val;
        if(root.left) getInfo(root.left, x, parent, depth+1);
        if(root.right) getInfo(root.right, x, parent, depth+1);
    }
    
}

在示例一中,我得到了我想要的返回 obj。

在示例二中,我得到了未定义。

如何理解递归的返回部分?我有我的基本情况“if(root.val === x) return obj;” 为什么这还不够。在示例二中,我认为它应该工作的方式。一旦 root.val == x 它只是将 obj 返回给 xInfo 和 yInfo,为什么示例 1 中的返回很重要。

我是否需要重新审视调用堆栈与搜索的交互方式?我不明白,我错过了什么。我越想越困惑。示例 1 我只是通过到处发送垃圾邮件来得出的

【问题讨论】:

  • 马上你就有了const xInfo = getInfo(root, x, null, 0); ...如果没有回报,这将如何运作?

标签: javascript recursion tree binary-search-tree


【解决方案1】:

return从当前递归函数调用返回到上一个递归调用,而不是整个递归调用系列。

当您到达基本情况时,return obj;obj 返回到上一个递归调用。

如果之前的递归调用是:

 let left =  getInfo(root.left, x, parent, depth+1);
 if(left) return left;

基本情况的结果存储到left,然后返回给调用它的递归调用。最终,所有函数都返回到调用它们的函数,这最终导致将值返回到isCousins 中的xInfo

另一方面,如果之前的调用是这样的:

if(root.left) getInfo(root.left, x, parent, depth+1);

getInfo(root.left, x, parent, depth+1) 的计算结果是 obj,然后你什么也不做,所以它被丢弃了。


您需要使用returns 手动将在基本情况中找到的值传回堆栈。仅仅返回导致基本情况的调用是不够的。

【讨论】:

  • 是的,这完全有道理。我需要调用堆栈中的每个状态来返回 obj 而不仅仅是一个状态。我假设一旦我达到基本情况。它将它返回到左/右,他们将继续返回它直到我们到达第一个堆栈?
  • @Momu 基本上是的。我在脑海中将其视为“调用链”或树,并且在叶子中找到的值需要手动传回才能到达根。如果你像我一样有视觉效果,你可能会发现画出来会有帮助。
猜你喜欢
  • 2013-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-08
  • 2022-01-03
  • 2017-07-26
  • 1970-01-01
相关资源
最近更新 更多