class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new LinkedList<>();
if (root == null) {
return res;
}
Deque<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
List<Integer> level = new LinkedList<>();
int size = queue.size();
while (size > 0) {
TreeNode node = queue.poll();
level.add(node.val);
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
size--;
}
res.add(level);
}
return res;
}
}
res.size() < index
:每一层只能添加一个链表用来存储本层节点的值class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new LinkedList<>();
if (root == null) {
return res;
}
dfs(1, res, root);
return res;
}
public void dfs(int index, List<List<Integer>> res, TreeNode root) {
if (root == null) {
return;
}
// 每层只能添加一个链表
if (res.size() < index) {
res.add(new LinkedList<>());
}
// 将节点的值添加道本层的链表中
res.get(index-1).add(root.val);
dfs(index+1, res, root.left);
dfs(index+1, res, root.right);
}
}
原文:https://www.cnblogs.com/linzedian/p/14098340.html