TreeNode root
  1. import java.util.*;
  2.  
  3. class treenode {
  4.   int val;
  5.   treenode left;
  6.   treenode right;
  7.  
  8.   treenode(int x) {
  9.     val = x;
  10.   }
  11. };
  12.  
  13. class LevelOrderTraversal {
  14.   public static List<List<Integer>> traverse(treenode root) {
  15.     List<List<Integer>> result = new ArrayList<List<Integer>>();
  16.     if (root == null)
  17.       return result;
  18.  
  19.     Queue<TreeNode> queue = new LinkedList<>();
  20.     queue.offer(root);
  21.     while (!queue.isEmpty()) {
  22.       int levelSize = queue.size();
  23.       List<Integer> currentLevel = new ArrayList<>(levelSize);
  24.       for (int i = 0; i < levelSize; i++) {
  25.         treenode currentNode = queue.poll();
  26.         // add the node to the current level
  27.         currentLevel.add(currentNode.val);
  28.         // insert the children of current node in the queue
  29.         if (currentNode.left != null)
  30.           queue.offer(currentNode.left);
  31.         if (currentNode.right != null)
  32.           queue.offer(currentNode.right);
  33.       }
  34.       result.add(currentLevel);
  35.     }
  36.  
  37.     return result;
  38.   }
  39.  
  40.   public static void main(string[] args) {
  41.     treenode root = new treenode(12);
  42.     root.left = new treenode(7);
  43.     root.right = new treenode(1);
  44.     root.left.left = new treenode(9);
  45.     root.right.left = new treenode(10);
  46.     root.right.right = new treenode(5);
  47.     List<List<Integer>> result = LevelOrderTraversal.traverse(root);
  48.     system.out.println("Level order traversal: " + result);
  49.   }
  50. }
  51.  
Parsed in 0.027 seconds