Populating Next Right Pointers in Each Node | LeetCode | Java

tanujav

Tanuja V

Posted on June 8, 2024

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

💖 💪 🙅 🚩
tanujav
Tanuja V

Posted on June 8, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related