Skip to content
目录

层序遍历

层序遍历的关键点是每次循环要遍历完完整的一层,然后才能进入下一层。

js
function levelOrder(root) {
  let res = [];
  if (!root) return res;
  let queue = [root];
  while (queue.length) {
    let len = queue.length;
    for (let i = 0; i < len; i++) {
      let node = queue.shift();
      res.push(node.val);
      if (node.left) queue.push(node.left);
      if (node.right) queue.push(node.right);
    }
  }
  return res;
}

If there is any reprint or CV, please mark the original address of this website