Working hacky solution in Javascript, but displeased with site


  • 0
    J

    Got this working after trying to figure out why my other solution wasn't working.

    var isSameTree = function(p, q) {    
        return JSON.stringify(p) === JSON.stringify(q);
    };
    

    My complaint is that the question specifies the inputs as TreeNodes, yet the first test sample inputs empty arrays. If the expectation is for us to do type checking inside the solution, please state so, since that adds more complexity unrelated to the problem at hand.

    My first attempt failed since using a check like if(p.val !== q.val) return false doesn't handle the null which could be passed in via recursion. So I tried if(pl !== q) return false, but that also fails in the case of arrays since array comparison in JS is not straight forward. See this SO post about how to do it. For a question dealing with binary tree comparison, adding logic to handle array comparison seems absurd.

    Also, tried a variety of methods on my local pc, which ran fine, but kept throwing errors the run code and submit solution site executions. This if (p.right && q.right isSameTree(p.right, q.right) === false) for some reason kept blowing up saying TypeError: Cannot read property 'right' of null when the inputs were listed as empty arrays. I'm not sure at what point it would check a property of an undefined or null object since I'm checking for the existence of it before entering the recursion.

    Am I missing something obvious here?


  • 0
    J

    Definitely will not pass as working solution in an interview.


  • 0
    V

    inputs are displayed as arrays because it is hard to display a binary tree on a website. the actual input will be an actual node: for example you can compare the node to null (if p != null) for example.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.