DEV Community

Tanuja V
Tanuja V

Posted on • Edited on

4 1 1

Populating Next Right Pointers in Each Node | LeetCode | Java


class Solution {
    public Node connect(Node root) {

        if(root==null)
            return root;

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

        queue.add(root);


        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i=0; i<size; i++){
               Node node = queue.remove();

               if(i<size-1)
               node.next = queue.peek();

              if(node.left != null)
                  queue.add(node.left);

               if(node.right!=null)
                  queue.add(node.right);

            }
        }

        return root;
    }
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading :)
Feel free to comment and like the post if you found it helpful
Follow for more 🤝 && Happy Coding 🚀

If you enjoy my content, support me by following me on my other socials:
https://linktr.ee/tanujav7

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs