CoderByte Binary Tree constructor problem

Dear Developers, I got stacked by the following coding solution. I was studying on Binary Tree constructor problem and found this solution. but I don’t understand some points. at the last if condition we see we are checking children[child] if true then it will return false. At the first time it is empty but when else condition execute that means we are assigning something children[child] why it is again gives false in next if checking ? first time it was empty but next steps we are assigning something . and If I try to push anything using children[child].push(child); it doesn’t not works but when I try to push anything to parents[parent].push(child); it works. It makes me strange actually. Anybody Can explain what is going on there ? Thank you

function TreeConstructor(strArr) { 


 let parents={};
 let children={};


for(let i=0; i<strArr.length; i++){
    
    let pair = strArr[i].replace(/[()]/g,"").split(",");
    
    let child = pair[0];
    let parent = pair[1];
    
    if(parents[parent]){
       parents[parent].push(child);
    }else{
     parents[parent]=[child];
    }
    
    if(parents[parent].length > 2){
      return false;
    }
    
    if(children[child]){
     return false;
    } else {
       children[child]=parent;
    }
    
    
}

return true;


}

TreeConstructor(["(1,2)", "(2,4)", "(5,7)", "(7,2)", "(9,5)"]);

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.