chencl1986 / Blog

Welcome to lee's blog.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

LeetCode题解:429. N叉树的层序遍历,BFS,JavaScript,详细注释

chencl1986 opened this issue · comments

原题链接:https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal/

解题思路:

  1. 该题可以使用BFS,逐层遍历二叉树。
  2. 使用队列进行遍历,队列中按顺序存储了每一层的节点。
  3. 每次循环时,将队列中当前层的节点依次取出,即可在这次循环中,获取到当前层所有节点的值。
  4. 同时,将当前层每个节点的子节点,依次存入队列尾部,等待下一次遍历处理。
  5. 不断重复步骤3、4,即可完成层序遍历。
/**
 * @param {Node} root
 * @return {number[][]}
 */
var levelOrder = function (root) {
  let result = []; // 存储层序遍历结果
  let queue = []; // 使用队列进行层序遍历,队列中存储的是每一层的所有节点
  root && queue.push(root); // 如果树存在,才进行遍历

  // 不断遍历队列,直到队列为空时,完成树的层序遍历
  while (queue.length) {
    // 缓存当前层的节点数量,确认队列的出队元素数量
    let queueLen = queue.length;
    result.push([]); // 在result中存入一个数组,用于存储当前层的节点值

    // 当前层有多少个节点,就进行多少次循环取出节点
    while (--queueLen >= 0) {
      // 将当前层的节点依次从队列取出
      const node = queue.shift();

      // 将当前层的数据存入result
      result[result.length - 1].push(node.val);

      // 如果子节点存在,则将子节点入队,作为下一层的节点
      if (node.children) {
        for (let i = 0; i < node.children.length; i++) {
          queue.push(node.children[i]);
        }
      }
    }
  }

  return result;
};