AFFILIATE LINKS
Great resource I use to learn algorithms.
40% off Tech Interview Pro: http://techinterviewpro.com/terriblewhiteboard
20% off CoderPro: http://coderpro.com/terriblewhiteboard
Here is the full implementation.
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
let levelOrderBottom = function(root) {
let result = [];
if (root === null) {
return result;
}
let queue = [];
queue.push(root);
while (queue.length !== 0) {
let nodeCount = queue.length;
let rowResult = [];
while (nodeCount > 0) {
let currentNode = queue.shift();
if (currentNode.left !== null) {
queue.push(currentNode.left);
}
if (currentNode.right !== null) {
queue.push(currentNode.right);
}
rowResult.push(currentNode.val);
nodeCount--;
}
result.unshift(rowResult);
}
return result;
};