【树】C004_N叉树的层序遍历(递归 | 迭代)

一、题目描述

Given an n-ary tree, return the level order traversal of its nodes' values.
Nary-Tree input serialization is represented in their level order traversal, 
each group of children is separated by the null value (See examples).

Input: root = [1,null,3,2,4,null,5,6]
Output: [[1],[3,2,4],[5,6]]

二、题解

N 叉树层次遍历模板代码:只要求遍历顺序一致,不要求结果的格式。

while (!queue.isEmpty()) {
  Node node = queue.poll();	
  val_list.add(node.val);
  for (Node child : node.children) {
    queue.add(child);
  }
}

方法一:递归

可参考二叉树的递归层次遍历核心代码:

if (level_list.size() == level) {
  level_list.add(new LinkedList<>());
}
level_list.get(level).add(root.val);

if (root.left != null)
  F(root.left, level + 1);
if (root.right != null)
  F(root.right, level + 1);

N叉树与二叉树的层次遍历大同小异,核心代码有二:

  • 当 level_list 的大小(即总层)等于当前遍历的层数时,需要构造新的列表存储当前层的所有结点。
  • 递归遍历所有子节点。
ArrayList<List<Integer>> level_List = null;
public List<List<Integer>> levelOrder1(Node root) {
  
  level_List = new ArrayList<List<Integer>>();
  if (root != null)
    dfs(root, 0);
  
  return level_List;
}


private void dfs(Node root, int level) {
 
  if (level_List.size() == level) {
    level_List.add(new LinkedList<>());
  }
  level_List.get(level).add(root.val);//添加到对应层
  
  if (root.children != null) {
    for (Node child : root.children) //当前层的下一层的所有结点
      dfs(child, level + 1);		
  }
}

复杂度分析

  • 时间复杂度: O ( N ) O(N)
  • 空间复杂度: O ( h ) O(h) ,h 在一般情况下是 log(N);极端情况是 O(n),因为树极端形态是链表。

方法二:迭代

算法

  • 要求的格式就是在构造下一层的列表时,需要创建新的子列表,然后将该层的所有节点的值插入到该子列表中。
  • 同样地,我们应该用一个 cur_level_size 记录当前层的结点个数,避免多加。
public List<List<Integer>> levelOrder(Node root) {
  LinkedList<List<Integer>> resList = new LinkedList<List<Integer>>();
  if (root == null)
    return resList;
  
  Queue<Node> queue = new LinkedList<>();
  queue.add(root);

  while (!queue.isEmpty()) {
    int curr_level_size = queue.size();
    LinkedList<Integer> item = new LinkedList<>();
    for (int i = 0; i < curr_level_size; i++) {	//当前层的所有结点
      Node node = queue.poll();
      item.add(node.val);
      queue.addAll(node.children);				//下一层的所有结点
    }
    resList.add(item);
  }
  return resList;
}

复杂度分析

  • 时间复杂度: O ( N ) O(N)
  • 空间复杂度: O ( N ) O(N)
发布了419 篇原创文章 · 获赞 94 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_43539599/article/details/104512046