ID | Title | Difficulty | |
---|---|---|---|
Loading... |
102. Binary Tree Level Order Traversal
Medium
LeetCode
Tree, Breadth-First Search, Binary Tree
Problem
Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
For example: Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
Code
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if(root == null) return new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
List<List<Integer>> res = new ArrayList<>();
while(!queue.isEmpty()){
int size = queue.size();
List<Integer> level = new ArrayList<>();
for(int i = 0; i < size; i++){
TreeNode curr = queue.poll();
level.add(curr.val);
if(curr.left != null) queue.offer(curr.left);
if(curr.right != null) queue.offer(curr.right);
}
res.add(level);
}
return res;
}
}
按 <- 键看上一题!
101. Symmetric Tree
按 -> 键看下一题!
103. Binary Tree Zigzag Level Order Traversal