Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth (e.g., if you have a tree with depth D,you'll have D linked lists).
/*Use BFS to travel the tree level by level*/ import java.util.*; public class LevelTravel { public List<List<TreeNode>> levelOrder(TreeNode root) { List<List<TreeNode>> result = new ArrayList<List<TreeNode>>(); List<TreeNode> temp1 = new ArrayList<TreeNode>(); List<TreeNode> temp2 = new ArrayList<TreeNode>(); if(root != null) temp1.add(root); while(temp1.isEmpty() == false) { ArrayList<TreeNode> array = new ArrayList<TreeNode>(); for(TreeNode node : temp1) { array.add(node); if(node.left != null) temp2.add(node.left); if(node.right != null) temp2.add(node.right); } result.add(array); temp1.clear(); for(TreeNode node : temp2) { temp1.add(node); } temp2.clear(); } return result; } }