【发布时间】:2022-01-30 08:57:55
【问题描述】:
var lowestCommonAncestor = function(root, p, q) {
// return the path to the node
let path = []
const search = (node, target) => {
if (node === null) return false
path.push(node)
if (node === target) return true
const leftSearched = search(node.left, target)
if (leftSearched) return true
const rightSearched = search(node.right,target)
if (rightSearched) return true
path.pop()
}
search(root, p)
const pathP = path
path = []
search(root, q)
const pathQ = path
let result
while(pathP.length > 0 && pathQ.length > 0 && pathP[0] === pathQ[0]) {
result = pathP[0]
pathP.shift()
pathQ.shift()
}
return result
};
console.log(lowestCommonAncestor([3,5,1,6,2,0,8,null,null,7,4],5,1));
我收到以下错误消息 const leftSearched = search(node.left, target) ^ 类型错误:无法读取未定义的属性“左”
谁能帮我解决这个问题
【问题讨论】:
-
node是一个数组。我真的不确定你为什么期望node.left或node.right存在。这不应该是某种树结构吗?您在哪里尝试将 Array 转换为此树结构? -
Console.log it out... 你需要调试一下。我可以告诉你 node 是未定义的,你想访问它的“left”属性。
-
@SebastianSimon 我已将问题发布在图片中以供参考
-
@suriyan 将数组转换为二叉树是任务的一部分。你还没有这样做。
-
@SebastianSimon ,作为解决方案的一部分,他们给出了这个函数 TreeNode(val) { this.val = val; this.left = this.right = null;但我不知道如何将数组转换为二叉树
标签: javascript binary-search-tree