Skip to content

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

@chencl1986

Description

@chencl1986

原题链接:429. N叉树的层序遍历

解题思路:

  1. 使用递归首先要思考,当前递归函数运行的是第n次递归,那么当前要做哪些处理。
  2. 先考虑的是,假设此时遍历到了最后一个节点为null,要给递归设置终止条件。
  3. 该题要求按层输出结果,因此需要一个index标识当前所在的层。
  4. 在当前递归,使用传入的index作为参数,遍历下一层节点时,将index+1。
/**
 * // Definition for a Node.
 * function Node(val,children) {
 *    this.val = val;
 *    this.children = children;
 * };
 */
function recursion(node, res, index) {
  // 如果当前节点不存在,则退出递归
  if (!node) {
    return;
  }

  // 将节点的值,按照当前层的index存入结果
  res[index] ? res[index].push(node.val) : (res[index] = [node.val]);
  // 计算下一层的index
  let newIndex = index + 1;

  // 遍历子节点,并传入下一层的index
  for (let i = 0; i < node.children.length; i++) {
    recursion(node.children[i], res, newIndex);
  }
}
/**
 * @param {Node} root
 * @return {number[][]}
 */
var levelOrder = function (root) {
  let result = []; // 储存结果

  // 递归遍历所有节点
  recursion(root, result, 0);

  return result;
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions