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

如何编写JavaScript二叉树比较函数?已写代码遇引用错误求助

Fixing "ReferenceError: compare is not defined" in Binary Tree Comparison Function

Hey, let's fix that error you're seeing! The issue here is super straightforward—you've got a mismatch between the function name you defined and the one your test code is trying to call.

What's Causing the Error?

Your test code at line 116 is trying to invoke a function named compare, but the function you wrote is actually called binaryTreeCompare. JavaScript can't find a function named compare in scope, hence the ReferenceError.

Two Simple Fixes

You can choose either of these solutions to resolve the issue:

1. Rename your function to match the test code

Change your function definition from binaryTreeCompare to compare so it aligns with what your test expects:

const compare = (a, b) => {
  if(a==null && b==null){
    return true;
  }else if(a!=null && b!=null){
    return( a.data == b.data && compare(a.left, b.left) && compare(a.right, b.right) );
  } else return false;
}

2. Update the test code to use your function's actual name

If you want to keep binaryTreeCompare as the function name, modify your test code to call binaryTreeCompare(a, b) instead of compare(a, b).

Quick Check: Your Comparison Logic is Correct!

Just to confirm—your core logic for comparing the binary trees is spot-on:

  • Returns true when both nodes are null (matching empty structure)
  • Recursively checks node values and left/right subtrees when both nodes exist
  • Returns false immediately if one node exists and the other doesn't (mismatched structure)

Full Working Example

Here's a complete, testable version using the first fix (renaming the function to compare):

class TreeNode {
  constructor(data, left=null, right=null) {
    this.data = data;
    this.left = left;
    this.right = right;
  }
}

const compare = (a, b) => {
  if(a==null && b==null){
    return true;
  }else if(a!=null && b!=null){
    return( a.data == b.data && compare(a.left, b.left) && compare(a.right, b.right) );
  } else return false;
}

// Test cases
const treeA = new TreeNode(5, new TreeNode(3), new TreeNode(7));
const treeB = new TreeNode(5, new TreeNode(3), new TreeNode(7));
const treeC = new TreeNode(5, new TreeNode(2), new TreeNode(7));

console.log(compare(treeA, treeB)); // Output: true
console.log(compare(treeA, treeC)); // Output: false

内容的提问来源于stack exchange,提问作者lasabahebwa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:34:06