DFS: better memory, faster
time: O(h): average, O(n): worst
/**
* 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[][]}
*/
let answer = [];
var levelOrder = function(root) {
answer = [];
findLevel(root);
return answer;
};
function findLevel(node, level = 0) {
if (node === null) return;
answer[level] = answer[level] ?? [];
answer[level].push(node.val);
findLevel(node.left, level + 1);
findLevel(node.right, level + 1);
}
/**
* 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[][]}
*/
let answer = [];
let q = [];
var levelOrder = function(root) {
answer = [];
q = [[root, 0]];
while (q.length > 0) {
const [node, level] = q.shift();
if (node === null) continue;
if (answer[level] === undefined) {
answer[level] = [];
}
answer[level].push(node.val);
q.push([node.left, level + 1]);
q.push([node.right, level + 1]);
}
return answer;
};