二叉树代码报错:Cannot read property 'data' of undefined 求助
Let's figure out why you're getting this inconsistent error and how to fix it once and for all.
What's causing the error?
Your TypeError: Cannot read property 'data' of undefined pops up because sometimes the node parameter passed to your searchTree recursive function is undefined. Here's the breakdown:
Node constructor uses undefined instead of null for defaults
YourNodeclass doesn't set default values forleftandright, so when you create a new node withnew Node(data), those properties becomeundefined(notnull). But in youraddmethod, you're using strict equality (===) to check ifnode.leftornode.rightisnull. Sinceundefined !== null, the code incorrectly assumes there's a valid child node and callssearchTree(node.left)/searchTree(node.right)withundefinedas the argument. When the recursive function tries to accessundefined.data, it throws the error.Typo breaks the levelOrder traversal
You have a typo in thelevelOrdermethod:node.rigthshould benode.right. This causes two problems:- You never add right child nodes to your traversal queue, so the level-order traversal won't work correctly.
- Since
node.rigthisundefined, the conditionnode.rigth !== nullevaluates totrue(becauseundefined !== null), so you pushundefinedinto the queue. Later iterations will try to access properties on thisundefinedvalue, triggering similar errors.
Fixed code
Here's your code with all issues resolved:
class Node { // Set default values for left/right to null constructor(data, left = null, right = null) { this.data = data; this.left = left; this.right = right; } } class BST { constructor() { this.root = null } add(data) { const node = this.root if (node === null) { this.root = new Node(data) return } else { const searchTree = function (node) { if (data < node.data) { // Check for falsy values (null/undefined) instead of strict null if (!node.left) { node.left = new Node(data) return } else { return searchTree(node.left) } } else if (data > node.data) { if (!node.right) { node.right = new Node(data) return } else { return searchTree(node.right) } } else { return null // Ignore duplicate values } } return searchTree(node) } } levelOrder() { const arr = []; const queue = []; let node = this.root; // Handle empty tree to avoid pushing null into the queue if (!node) return arr; queue.push(node); while(queue.length) { node = queue.shift(); arr.push(node.data); // Push actual data instead of node objects (optional but useful) if(node.left !== null) queue.push(node.left); if(node.right !== null) queue.push(node.right); // Fixed typo here } return arr; // Return the traversal result } } const tree = new BST() tree.add(1) tree.add(2) tree.add(3) tree.add(4) tree.add(5) console.log(tree.levelOrder()) // Should log [1,2,3,4,5]
Key concepts to deepen your understanding
- Null vs. Undefined in JavaScript: These are distinct values, but often used to represent "no value". Strict equality (
===) differentiates them, while loose equality (==) treats them as equal. For data structures like trees, standardize onnullfor empty references to avoid confusion. - Recursion Boundaries: Recursive functions need clear exit conditions to prevent passing invalid values (like
undefined) into the recursive call. Always validate inputs before accessing their properties. - Constructor Initialization: Setting default values in class constructors ensures all instance properties start in a predictable state, which prevents unexpected behavior in later logic.
内容的提问来源于stack exchange,提问作者Momu

