/*
// 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 {
private List<List<Integer>> list = new ArrayList<>();
public List<List<Integer>> levelOrder(Node root) {
DFS(root);
return list;
}
void DFS(Node node) {
//定义队列
Queue<Node> queue = new LinkedList<>();
if (node == null) return;
queue.offer(node);
while (!queue.isEmpty()) {
int len = queue.size();//获取本层的节点个数
List<Integer> temp=new ArrayList<>();
while (len > 0) {//进行本次节点对应值的统计,并将下一层节点加入队列中
Node poll = queue.poll();
temp.add(poll.val);
if (poll.children != null && poll.children.size() != 0) {//若有子节点
for (Node child : poll.children) {
if (child != null) {
queue.offer(child);
}
}
}
len--;
}
list.add(temp);
}
}
}
class Solution {
private List<Integer> list = new ArrayList<>();
public List<Integer> largestValues(TreeNode root) {
DFS(root);
return list;
}
void DFS(TreeNode node) {
//定义队列
Queue<TreeNode> queue = new LinkedList<>();
if (node == null) return;
queue.offer(node);
while (!queue.isEmpty()) {
int len = queue.size();//获取本层的节点个数
int max=-2147483648;
while (len > 0) {//进行本次节点对应值的统计,并将下一层节点加入队列中
TreeNode poll = queue.poll();
max = max > poll.val ? max : poll.val;
if (poll.left != null) queue.offer(poll.left);
if (poll.right != null) queue.offer(poll.right);
len--;
}
list.add(max);
}
}
}