binary-tree-level-order.js (1198B)
1 //Given a binary tree return the values in it as an array of arrays 2 //where each array is a single layer of the tree. 3 //Ex. 4 // 2 5 // 3 4 6 // 6 8 7 //Output of the above tree would be: [[2][3,4][6,8]] 8 //My solution uses BFS to traverse each layer adding all of the values to an array 9 //the time complexity of this is O(n) where n is the number of listnodes in the tree. 10 //Time: 60ms Beats: 82.33% 11 //Memory: 44.8MB Beats: 12.51% 12 13 var levelOrder = function(root) { 14 if(root == null){ 15 return []; 16 } 17 if(root.left == null && root.right == null){ 18 return [[root.val]]; 19 } 20 let levels = []; 21 let queue = new Array(); 22 let level = 0 23 queue.splice(0,0,root); 24 while(queue.length != 0){ 25 let start_len = queue.length; 26 levels.push([]); 27 for(let i = 0 ; i < start_len ; ++i){ 28 let curr_node = queue.pop(); 29 levels[level].push(curr_node.val); 30 if(curr_node.left != null){ 31 queue.splice(0,0,curr_node.left); 32 } 33 if(curr_node.right != null){ 34 queue.splice(0,0,curr_node.right); 35 } 36 } 37 level += 1; 38 } 39 return levels; 40 };