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

例如,给定一个 3叉树 :

leetcode 429. N叉树的层序遍历

返回其层序遍历:

[
     [1],
     [3,2,4],
     [5,6]
]

说明:

  1. 树的深度不会超过 1000
  2. 树的节点总数不会超过 5000

递归实现

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

    public Node() {}

    public Node(int _val,List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> result = new ArrayList<>();
        helper(result,root,0);
        return result;
    }
    
    public void helper(List<List<Integer>> ret,Node root,int level){
        if(root == null){
            return;
        }
        if(level >= ret.size()){
            ret.add(new ArrayList<Integer>());
        }
        ret.get(level).add(root.val);
        for(Node node:root.children){
            helper(ret,node,level + 1);
        }
        return;
    }
}

队列实现

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

    public Node() {}

    public Node(int _val,List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
    public List<List<Integer>> levelOrder(Node root) {
        if(root == null){
            return new ArrayList<List<Integer>>();
        }
        Queue<Node> queue = new LinkedList<>();
        List<List<Integer>> result = new ArrayList<>();
        queue.add(root);
        while(queue.size() != 0){
            List<Integer> list = new ArrayList<>();
            int size = queue.size();
            for(int i = 0;i < size;i++){
                Node node = queue.poll();
                queue.addAll(node.children);
                list.add(node.val);
            }
            result.add(list);
        }
        return result;
    }
}

 

相关文章:

  • 2021-08-25
  • 2021-11-07
  • 2022-12-23
  • 2021-10-05
  • 2021-05-06
  • 2021-09-11
  • 2021-10-02
猜你喜欢
  • 2021-06-23
  • 2021-10-13
  • 2022-01-07
  • 2021-07-08
  • 2022-12-23
  • 2021-12-16
相关资源
相似解决方案