二叉树最近公共祖先(LCA)求解代码报错:TypeError: Cannot read property 'left' of undefined 修复请求
修复二叉树最近公共祖先代码的 TypeError 问题
首先咱们得揪出错误的根源:你调用函数时传入的是一个数组和两个数字,但你的代码逻辑是基于二叉树节点对象来写的。数组里的元素是普通数字,它们没有left/right属性,当search函数尝试访问node.left时,自然就会抛出"Cannot read property 'left' of undefined"的错误。
接下来咱们一步步修复这个问题:
1. 定义二叉树节点构造函数
首先需要明确二叉树节点的结构,每个节点应该包含val(值)、left(左子节点)、right(右子节点)三个属性:
function TreeNode(val) { this.val = val; this.left = this.right = null; }
2. 实现数组转二叉树的工具函数
把你传入的数组转换成符合要求的二叉树节点结构:
function arrayToTree(arr) { if (!arr.length) return null; const root = new TreeNode(arr[0]); const queue = [root]; let i = 1; while (queue.length && i < arr.length) { const node = queue.shift(); if (arr[i] !== null) { node.left = new TreeNode(arr[i]); queue.push(node.left); } i++; if (i < arr.length && arr[i] !== null) { node.right = new TreeNode(arr[i]); queue.push(node.right); } i++; } return root; }
3. 调整原函数的调用逻辑
原函数里的node === target是判断节点引用是否相等,所以不能直接传数字5和1,得先找到对应的节点对象;另外原search函数最后缺少return false的语句,当左右子树都没找到目标时需要明确返回false,否则上层递归会得到undefined导致逻辑异常:
var lowestCommonAncestor = function(root, p, q) { 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() // 明确返回false,告知上层递归未找到目标 return false } search(root, p) const pathP = [...path] // 用扩展运算符做浅拷贝,避免后续清空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 }; // 转换数组为二叉树 const root = arrayToTree([3,5,1,6,2,0,8,null,null,7,4]); // 找到对应的p和q节点 function findNode(root, val) { if (!root) return null; if (root.val === val) return root; return findNode(root.left, val) || findNode(root.right, val); } const p = findNode(root, 5); const q = findNode(root, 1); // 调用函数并打印结果值 console.log(lowestCommonAncestor(root, p, q).val); // 输出3
内容的提问来源于stack exchange,提问作者suriyan
相关产品推荐
相关产品推荐

