Binary Tree Level Order Traversal
ID: 69; easy
Solution 1 (Java)
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: A Tree
* @return: Level order a list of lists of integer
*/
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> list = new ArrayList<>();
if (root == null) return list;
Queue<TreeNode> q = new ArrayDeque<>();
q.offer(root);
while (!q.isEmpty()) {
int size = q.size();
List<Integer> level = new ArrayList<>();
for (int i = 0; i < size; i++) {
TreeNode curr = q.poll();
level.add(curr.val);
if (curr.left != null)
q.offer(curr.left);
if (curr.right != null)
q.offer(curr.right);
}
list.add(level);
}
return list;
}
}
Notes
Classic BFS
Last updated