题目
93、N叉树的层序遍历
93、N叉树的层序遍历

思路很简单,跟之前的二叉树的遍历基本类似,一个队列用来存放所有的节点,注意的是一层的遍历需要将值放入到size,因为队列的值是不断变化的
写的比较快,也没出现多大的bug,只是一开始把根节点放入两次了,调试了一下bug

/*
// 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<>();
	     List<Integer> tem = new ArrayList<>();
	     Deque<Node> nodes = new LinkedList<>();
	     if(root == null){
	    	 return result;
	     }else {
			 nodes.offer(root);
			while (!nodes.isEmpty()) {
				tem = new ArrayList<>();
				List<Node> tem2 = new ArrayList<>();
				int size = nodes.size();	
				for (int i = 0; i < size; i++) {
					Node node1 = nodes.poll();
					
					tem.add(node1.val);
					tem2 = node1.children;
					for (Node node : tem2) {
						nodes.offer(node);
					}
				}
				result.add(tem);
			}
		}
	     
	     return result;
    }
}

用时还行
93、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>> res=new ArrayList<List<Integer>>();
    public List<List<Integer>> levelOrder(Node root) {
    	bfs(root,0);
    	return res;
    }
    public void bfs(Node root,int level) {
    	if(root==null) {
    		return ;
    	}
    	if(level==res.size())res.add(new ArrayList<>());
    	res.get(level).add(root.val);
    	for(Node node:root.children) {
    		bfs(node,level+1);
    	}
    }
}

相关文章:

  • 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-17
  • 2021-11-20
  • 2022-01-07
相关资源
相似解决方案