Sunday, 23 January 2022

Level Order Traversal

 Level Order Traversal:

Level by Level
Approch

    1. Created a Queue,
    2. push the root and null
    3. in while loop traverse the tree
    4. create temp print and pop the root 
    5. push the left and right of the root and continue the while loop 
    

static void printlevelOrder(Node root) {
        Queue<Node> q = new LinkedList<Node>();
        q.add(root);
        q.add(null);
        while (!q.isEmpty()) {
            Node curr = q.poll();
            if (curr == null) {
                if (q.isEmpty()) {
                    return;
                }
                q.add(null);
                System.out.println();
                continue;
            }
            System.out.print(curr.data + " ");
            if (curr.left != null) {
                q.add(curr.left);
            }
            if (curr.right != null) {
                q.add(curr.right);
            }
        }
    }

No comments:

Post a Comment