面向小白的力扣429. N 叉树的层序遍历

133 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第15天,点击查看活动详情

今天,我们继续搞算法。

题目描述

给定一个 N 叉树,返回其节点值的层序遍历。(即从左到右,逐层遍历)。

树的序列化输入是用层序遍历,每组子节点都由 null 值分隔(参见示例)。

image.png

题目分析

这个题目是让我们返回其节点值的层序遍历。(即从左到右,逐层遍历)

层序遍历很简单就是广度优先遍历,遍历一层之后是下一层,root = [1,null,3,2,4,null,5,6]这个1是最上层,之后是3,2,4,然后是5,6,所以是[[1],[3,2,4],[5,6]]。

我们对结果进一步分析: [[1],[3,2,4],[5,6]]

[1] depth = 0 [3,2,4] depth = 1 [5,6] depth = 2

我们可以借助队列,先进先出的特点 把1取出,放 3,2,4 把3取出 放 5,6 依次放入 2,4,5,6,程序结束。

解题思路

  • 确定操作对象:本题中,操作对象1个root
  • 确定操作条件:如果对象为空,就下一个,如果层数大了,就要扩容。
  • 确定操作过程:操作过程为,取出对象和深度,对应放入对象值,然后遍历它的孩子,依次迭代。
  • 确定结果返回:返回最终结果。

代码

/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
     public List<List<Integer>> levelOrder(Node root) {
        Queue<Pair<Node,Integer>> q = new LinkedList<>();
        List<List<Integer>> seq = new ArrayList<List<Integer>>();
        q.add(new Pair<Node,Integer>(root,0));
        while(!q.isEmpty()){
            Node node = q.peek().getKey();
            Integer depth = q.poll().getValue();
            if(node == null) continue;
            if (seq.size()<=depth.intValue()) seq.add(new ArrayList<Integer>());
            seq.get(depth).add(node.val);
            for (Node children : node.children){
                q.add(new Pair<>(children,depth+1));
            }
        }
        return seq;

    }
}

总结

本题我们是使用了队列来完成这个N叉树的层序遍历,队列有个特点是先进先出嘛,我们取对头,然后把下一层的对头放入,再取下一层,封装结果并返回。