如何编写JavaScript二叉树比较函数?已写代码遇引用错误求助
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
truewhen both nodes arenull(matching empty structure) - Recursively checks node values and left/right subtrees when both nodes exist
- Returns
falseimmediately 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

