了解递归时的“返回”

问题描述

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

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

示例1:

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

const getInfo = (root,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,depth+1);
        if(left) return left;
        let right = getInfo(root.right,depth+1);
        if(right) return right;
    }
    
}

示例2:

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

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

在示例二中,我不确定。

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

我是否需要重新研究调用堆栈与搜索的交互方式?我不明白,我所缺少的。我思考的越多,我就越困惑。我只是通过向各处发送垃圾邮件得出的示例1

解决方法

return从当前的递归函数调用返回到先前的递归调用,而不是整个递归调用序列。

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

如果先前的递归调用是:

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

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

但是,另一方面,如果上一个呼叫是这样:

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

getInfo(root.left,depth+1)的值为obj,然后您对其不执行任何操作,因此将其丢弃。


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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...