Binary Tree Level Order Traversal
Description
doc
Solutions
First Idea
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function (root) {
if (!root) {
return []
}
let result = []
let curLevel = []
let curQueue = [root]
let nextQueue = []
while (curQueue.length) {
const cur = curQueue.shift()
curLevel.push(cur.val)
cur.left && nextQueue.push(cur.left)
cur.right && nextQueue.push(cur.right)
if (!curQueue.length) {
curQueue = nextQueue
nextQueue = []
result.push(curLevel)
curLevel = []
}
}
return result
}
- Time Complexity: O(n)
- Space Complexity: O(n)