You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

二叉树代码报错: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:

  1. Node constructor uses undefined instead of null for defaults
    Your Node class doesn't set default values for left and right, so when you create a new node with new Node(data), those properties become undefined (not null). But in your add method, you're using strict equality (===) to check if node.left or node.right is null. Since undefined !== null, the code incorrectly assumes there's a valid child node and calls searchTree(node.left)/searchTree(node.right) with undefined as the argument. When the recursive function tries to access undefined.data, it throws the error.

  2. Typo breaks the levelOrder traversal
    You have a typo in the levelOrder method: node.rigth should be node.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.rigth is undefined, the condition node.rigth !== null evaluates to true (because undefined !== null), so you push undefined into the queue. Later iterations will try to access properties on this undefined value, 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 on null for 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 07:12:44