# Accepted BFS and DFS Solutions JAVA

• BFS Solution

``````  public List<List<Integer>> levelOrder(TreeNode root) {

if(root==null) return new ArrayList<List<Integer>>();

ArrayDeque<TreeNode> q = new ArrayDeque<TreeNode>();

List<List<Integer>> result = new ArrayList<List<Integer>>();

while(!q.isEmpty()) {
int size = q.size(); //  level size
List<Integer> list = new ArrayList<Integer>();
for(int i=0; i < size; i++) {
TreeNode node = q.remove();
if(node.left != null) {
}
if(node.right != null) {
}
}
}

return result;
}
``````

DFS Solution

``````public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> list  =  new ArrayList<List<Integer>>();
if( root != null){
List<Integer> itemList = new ArrayList<Integer>();
dfs(root.left, root.right, 1, list);
}

return list;
}

public void dfs(TreeNode left, TreeNode right, int level, List<List<Integer>> list){
if(left == null && right == null) return;

if( list.size() == level){
}

List<Integer> itemList = new ArrayList<Integer>(list.get(level));

if(left != null) {
dfs(left.left, left.right, level + 1, list);
}

if(right != null) {