# Solving Leetcode Interviews in Seconds with AI: Populating Next Right Pointers in Each Node II


	# Introduction
	In this blog post, we will explore how to solve the LeetCode problem "117" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like [Chatmagic](https://www.chatmagic.app), we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

	# Problem Statement
	> Given a binary tree  struct Node {   int val;   Node *left;   Node *right;   Node *next; }  Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL.   Example 1:   Input: root = [1,2,3,4,5,null,7] Output: [1,#,2,3,#,4,5,7,#] Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.  Example 2:  Input: root = [] Output: []    Constraints:  The number of nodes in the tree is in the range [0, 6000]. -100 <= Node.val <= 100    Follow-up:  You may only use constant extra space. The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.  

	# Explanation
	Here's the approach, complexity analysis, and Python code for connecting nodes at the same level in a binary tree using constant extra space:

*   **Leverage Existing 'next' Pointers:** The solution cleverly uses the already established `next` pointers of the upper levels to connect nodes in the lower levels. This avoids the need for a queue or list to hold nodes at each level.
*   **Iterate Level by Level:** The algorithm effectively traverses the tree level by level. It begins at the root and iterates through each node in that level, using the `next` pointer to move to the right sibling. Within each level, it connects the `left` and `right` children appropriately.

*   **Time & Space Complexity:** O(N) time complexity where N is the number of nodes, and O(1) extra space complexity.

	
	# Code
	```python
	class Node:
    def __init__(self, val=0, left=None, right=None, next=None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next

def connect(root: Node) -> Node:
    """
    Connects nodes at the same level in a binary tree using constant extra space.
    """
    if not root:
        return None

    leftmost = root  # Start at the leftmost node of each level

    while leftmost:
        head = leftmost  # Head of the current level
        leftmost = None  # Reset leftmost for the next level

        while head:
            # Connect left child to right child (if both exist)
            if head.left:
                if head.right:
                    head.left.next = head.right
                else:
                    # if right child does not exist, connect left child to the next node's left child or right child.
                    temp = head.next
                    while temp:
                        if temp.left:
                            head.left.next = temp.left
                            break
                        if temp.right:
                            head.left.next = temp.right
                            break
                        temp = temp.next


            # Connect right child to the next node's left child (if exists)
            if head.right:
                temp = head.next
                while temp:
                    if temp.left:
                        head.right.next = temp.left
                        break
                    if temp.right:
                        head.right.next = temp.right
                        break
                    temp = temp.next

            # Find the leftmost node for the next level
            if not leftmost:
                if head.left:
                    leftmost = head.left
                elif head.right:
                    leftmost = head.right
            head = head.next
    return root
	```
			
