题目来源:

https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal/

题目描述:

LeetCode429.N叉树的层序遍历

代码如下:

/*
// 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 {
	List<List<Integer>> list = new ArrayList<List<Integer>>();

	public List<List<Integer>> levelOrder(Node root) {
		levelOrder(0, root);
		return list;
	}

	public void levelOrder(int level, Node root) {
		if (root == null)
			return;

		if (list.size() == level) {
			list.add(new ArrayList<>());
		}

		list.get(level).add(root.val);
		for (Node node : root.children) {
			levelOrder(level + 1, node);
		}
	}
}

 

相关文章:

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