DSA Day 88/100

DSA Day 88/100

Topic: Tree

1) Level order traversal Line by Line

Easy

          1
       /     \
     2        3
   /    \     /   \
  4     5   6    7
    \
     8
 1 $ 2 3 $ 4 5 6 7 $ 8 $.
 static ArrayList<ArrayList<Integer>> levelOrder(Node node) 
    {
        // we dont have to print out $, compiler will do it for us

        /*

        ArrayList<ArrayList<Integer>> means
        it is a 2 D list 
        each row is a separate list 

        **for example**

         ArrayList<ArrayList<Integer>> list2D = new ArrayList<>();

        // Create some inner ArrayLists and add them to the outer ArrayList

        ArrayList<Integer> innerList1 = new ArrayList<>();
        innerList1.add(1);
        innerList1.add(2);
        innerList1.add(3);

        ArrayList<Integer> innerList2 = new ArrayList<>();
        innerList2.add(4);
        innerList2.add(5);

        list2D.add(innerList1);
        list2D.add(innerList2);


        */



        ArrayList<ArrayList<Integer>> outertemp_arr = new ArrayList<ArrayList<Integer>>();

        // base conditions
        if (node==null){
            return outertemp_arr;
        }

        Queue<Node> temp_q = new LinkedList<>();

        // 1st row arraylist
        ArrayList<Integer> temp_list1 = new ArrayList<>();
        temp_list1.add(node.data);
        temp_q.add(node);
        temp_q.add(null);
        outertemp_arr.add(temp_list1);

        ArrayList<Integer> innertemp_list = new ArrayList<>();

        while(temp_q.size()>1){

            Node root = temp_q.poll();

            if(root==null){
                temp_q.add(null);
                outertemp_arr.add(innertemp_list);
                innertemp_list = new ArrayList<Integer>();
                continue;
            }

            if(root.left!=null){
                innertemp_list.add(root.left.data);
                temp_q.add(root.left);
            }
            if(root.right!=null){
                innertemp_list.add(root.right.data);
                temp_q.add(root.right);
            }

        }

        return outertemp_arr;

    }

Thank you for reading :)