Iterative JS solution (BFS algorithm)


  • 0
    R
    var isSameTree = function(p, q) {
        arrA = [p];
        arrB = [q];
        arrAnext = [];
        arrBnext = [];
        while(true) {
            for(var i = 0; i < arrA.length; i++) {
                if((arrA[i] === null && arrB[i] !== null) || (arrA[i] !== null && arrB[i] === null) || 
                (arrA[i] !== null && arrB[i] !== null && arrA[i].val !== arrB[i].val)) 
                    return false;
                else if(arrA[i] !== null && arrB[i] !== null) {
                    arrAnext.push(arrA[i].left);
                    arrAnext.push(arrA[i].right);
                    arrBnext.push(arrB[i].left);
                    arrBnext.push(arrB[i].right);
                }
            }
            if(arrAnext.length === 0)
                return true;
            
            arrA = arrAnext;
            arrB = arrBnext;
            arrAnext = [];
            arrBnext = [];
        }
    };

Log in to reply
 

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