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).
LeetCode-102: 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).

There are two ways to solve this problem. Let us first discuss the Breadth First Search (BFS) approach:
Queue to store the nodes of the tree.root node.value of the node to the current level.left and right children, add them to the queue.We can also solve this problem using a Depth First Search (DFS) recursive approach:
result list (List<List<Integer>>) to store the node values at each level.node and the level.level is equal to the size of the result, this means we have reached a new level which has not been iterated before. Create a new list for this level.left and right children and the level incremented by 1.Let us first implement the BFS approach:
public List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
List<List<Integer>> result = new ArrayList<>();
// handle the empty tree case
if(null != root){
queue.add(root);
}
while(!queue.isEmpty()){
int nodesAtCurrentLevel = queue.size();
List<Integer> nodeValues = new ArrayList<>();
while(nodesAtCurrentLevel > 0){
TreeNode node = queue.remove();
nodeValues.add(node.val);
nodesAtCurrentLevel--;
if(null != node.left){
queue.add(node.left);
}
if(null != node.right){
queue.add(node.right);
}
}
result.add(nodeValues);
}
return result;
}
Now, let us implement the DFS approach:
private final List<List<Integer>> nodesAtLevel = new ArrayList<>();
public List<List<Integer>> levelOrder(TreeNode root) {
if(null == root){
return nodesAtLevel;
}
traverse(root, 0);
return nodesAtLevel;
}
private void traverse(TreeNode node, int level){
if(nodesAtLevel.size() == level){
nodesAtLevel.add(level, new ArrayList<>());
}
List<Integer> nodeValues = nodesAtLevel.get(level);
nodeValues.add(node.val);
if(null != node.left){
traverse(node.left, level+1);
}
if(null != node.right){
traverse(node.right, level+1);
}
}
Assuming $N$ is the number of nodes in the binary tree and $H$ is the height of the binary tree:
Be notified of new posts. Subscribe to the RSS feed.