102. Binary Tree Level Order Traversal #
题目 #
给定二叉树的根节点 root
,返回其节点值的 层序遍历。
即逐层地,从左到右访问所有节点。
思路 #
代码 #
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ans = new LinkedList<>();
if (root == null) return ans;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (queue.size() != 0) {
ans.add(new LinkedList<>());
for (int i = 0, layerSize = queue.size(); i < layerSize; i++) {
TreeNode node = queue.poll();
ans.get(ans.size() - 1).add(node.val);
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
}
return ans;
}
}