medium
Given the root
of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
Input: root = [1]
Output: [[1]]
Input: root = []
Output: []
[0, 2000]
.-1000 <= Node.val <= 1000
/**
* Definition for a binary tree node.
* 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>> result = new ArrayList<>();
TreeNode rootNode = root;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int size = 0;
if (rootNode == null) {
return result;
}
while (queue.size() > 0) {
List<Integer> levelResult = new ArrayList<>();
size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode currentNode = queue.poll();
levelResult.add(currentNode.val);
if (currentNode.left != null) {
queue.offer(currentNode.left);
}
if (currentNode.right != null) {
queue.offer(currentNode.right);
}
}
result.add(levelResult);
}
return result;
}
}