【发布时间】: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