https://leetcode.com/problems/binary-tree-level-order-traversal
/**
- 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 res = [];
let queue = [root];
while(queue.length>0) {
let stack = [];
for(let i=queue.length; i>0; i--){
let cur = queue.shift();
stack.push(cur.val);
if(cur.left) {
queue.push(cur.left);
}
if(cur.right) {
queue.push(cur.right);
}
}
res.push(stack);
}
return res;
};
网友评论