javascriptalgorithmdata-structuresbinary-treebinary-search-tree

How do i write a function in JavaScript that compares two trees defined by TreeNodes a and b?


I'm trying to write a JavaScript function that compares two binary trees defined by TreeNodes a and b and returns true if they are equal in structure and in value and false otherwise.

for example example of comparing both values and structure of two binary trees

Given the following class:

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

Here is the code i tried writing so far comapring TreeNode a and b.

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

I expected an ouput of either true or false but this is what i get:

ReferenceError: compare is not defined
    at Context.it (test.js:116:16)

Solution

  • Solution to my own question after serious research is shown in the snippet below.

    function compare(a, b){
      if (!a && !b) {
          return true;
       } else if (!a || !b) {
          return false;
       } else {
          return a.val === b.val && compare(a.left, b.left) && compare(a.right, b.right);
       }
    }