We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
思路:依然是层序遍历,只是节点的孩子有多个了,children也是List类型的,将节点的所有孩子遍历后全部放入队列即可:
遍历方式
class Solution { public List<List<Integer>> levelOrder(Node root) { List<List<Integer>> result = new ArrayList<>(); Queue<Node> que = new LinkedList<>(); if (root != null) { que.offer(root); } while (!que.isEmpty()) { List<Integer> list = new ArrayList<>(); int len = que.size(); for (int i = 0; i < len; i++) { Node node = que.poll(); list.add(node.val);//取出节点的值加入到结果集 //添加节点的孩子到队列,是Node类型的List List<Node> children = node.children; //遍历孩子,放到队列中 // for (int j = 0; j < children.size(); j++) { // if (children.get(j) != null ) { // que.offer(children.get(j));//将节点加入到队列 // } // } for (Node child : children) { if (child != null) { que.offer(child); } } } result.add(list); } return result; } }
N叉树(节点)的定义:
// 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; } };
The text was updated successfully, but these errors were encountered:
No branches or pull requests
N叉树的层序遍历
N叉树(节点)的定义:
The text was updated successfully, but these errors were encountered: