My BFS javascript solution


  • 0
    J
    var levelOrderBottom = function(root) {
        var Arr = new Array();
    	var queue = new Array();
    	if(root!=null){
            root.layer =0;
            queue.push(root);
    	}
    	while (queue.length !== 0){
    	    var popNode = queue.shift();
    	    var layer = parseInt(popNode.layer);
    	    console.log("layer:"+layer);
    	    if(Arr[layer]==undefined){
    	        Arr[layer] = new Array();
    		}
            Arr[layer].push(popNode.val);
    	    /*左右节点压入*/
    	    if (popNode.left !== null ){
                popNode.left.layer = layer + 1;
                queue.push(popNode.left);
    		}
            if (popNode.right !== null ){
                popNode.right.layer = layer + 1;
                queue.push(popNode.right);
            }
    	}
    	return Arr.reverse();
    };

Log in to reply
 

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