2020-07-25 102. Binary Tree Leve
2020-07-25 本文已影响0人
苦庭
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;
};