LeetCode: Binary Tree Level Order Traversal Solution
Implementation
1/**2 * Definition for a binary tree node.3 * function TreeNode(val, left, right) {4 * this.val = (val===undefined ? 0 : val)5 * this.left = (left===undefined ? null : left)6 * this.right = (right===undefined ? null : right)7 * }8 */9/**10 * @param {TreeNode} root11 * @return {number[][]}12 */13// tree preorder traversal14var levelOrder = function (root) {15 const res = []1617 const recursion = (node, level = 0) => {18 if (!node) return1920 if (!res[level]) res[level] = []2122 res[level].push(node.val)2324 recursion(node.left, level + 1)25 recursion(node.right, level + 1)26 }2728 recursion(root, 0)2930 return res31}3233// bfs34var levelOrder = function (root) {35 const queue = []36 const res = []3738 if (!root) return res3940 queue.unshift(root)41 while (queue.length) {42 const currentQueueLength = queue.length43 const subList = []44 for (let i = 0; i < currentQueueLength; i++) {45 queue[0].left && queue.push(queue[0].left)46 queue[0].right && queue.push(queue[0].right)47 subList.push(queue.shift().val)48 }49 res.push(subList)50 }5152 return res53}
References
Comments
Loading comments...
Tags
leetcode
tree
bfs
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.