KatInterview

116. Populating Next Right Pointers in Each Node

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to populate a special next pointer for each node in a perfect binary tree. This pointer should link a node to its immediate right sibling on the same level. The main challenge lies in the follow-up constraint: the solution must use only constant extra space.

Solution

Populating Next Right Pointers in Each Node in Python

"""
# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""

class Solution:
    def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
        if not root:
            return None

        # `leftmost` is the starting node of the current level.
        leftmost = root
        
        # Loop condition: as long as there is a next level to process.
        while leftmost.left:
            # `head` is the cursor to traverse the current level.
            head = leftmost
            
            while head:
                # Connection 1: Connect left child to right child.
                # Both exist because it's a perfect binary tree.
                head.left.next = head.right
                
                # Connection 2: Connect right child to cousin.
                if head.next:
                    head.right.next = head.next.left
                
                # Move to the next node on the same level.
                head = head.next
            
            # Move to the next level.
            leftmost = leftmost.left
            
        return root

Populating Next Right Pointers in Each Node in Java

/*
// Definition for a Node.
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {}
    
    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
*/

class Solution {
    public Node connect(Node root) {
        if (root == null) {
            return null;
        }

        // `leftmost` is the starting node of the current level.
        Node leftmost = root;

        // The loop condition ensures we don't process the last level, which has no children.
        while (leftmost.left != null) {
            // `head` is used to traverse the current level.
            Node head = leftmost;

            while (head != null) {
                // Connection 1: Connect the left child to the right child.
                head.left.next = head.right;

                // Connection 2: Connect the right child to the next node's left child.
                if (head.next != null) {
                    head.right.next = head.next.left;
                }

                // Move to the next node in the current level.
                head = head.next;
            }
            
            // Move to the first node of the next level.
            leftmost = leftmost.left;
        }
        
        return root;
    }
}

Populating Next Right Pointers in Each Node in C++

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};
*/

class Solution {
public:
    Node* connect(Node* root) {
        if (root == nullptr) {
            return nullptr;
        }

        // `leftmost` is the starting node of the current level.
        Node* leftmost = root;

        // The loop condition ensures we don't process the last level, which has no children.
        while (leftmost->left != nullptr) {
            // `head` is used to traverse the current level.
            Node* head = leftmost;

            while (head != nullptr) {
                // Connection 1: Connect the left child to the right child.
                head->left->next = head->right;

                // Connection 2: Connect the right child to the next node's left child.
                if (head->next != nullptr) {
                    head->right->next = head->next->left;
                }

                // Move to the next node in the current level.
                head = head->next;
            }
            
            // Move to the first node of the next level.
            leftmost = leftmost->left;
        }
        
        return root;
    }
};

Populating Next Right Pointers in Each Node in TypeScript

/**
 * Definition for _Node.
 * class _Node {
 *     val: number
 *     left: _Node | null
 *     right: _Node | null
 *     next: _Node | null
 *     constructor(val?: number, left?: _Node, right?: _Node, next?: _Node) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function connect(root: _Node | null): _Node | null {
    if (root === null) {
        return null;
    }

    // `leftmost` is the starting node of the current level.
    let leftmost: _Node | null = root;

    // The loop iterates as long as there's a next level (i.e., children exist).
    while (leftmost.left !== null) {
        // `head` is used to traverse the nodes of the current level.
        let head: _Node | null = leftmost;

        while (head !== null) {
            // Connection 1: Connect left child to right child.
            // Since it's a perfect binary tree, if `left` is not null, `right` isn't either.
            head.left!.next = head.right;

            // Connection 2: Connect right child to the next node's left child.
            if (head.next !== null) {
                head.right!.next = head.next.left;
            }

            // Move to the next node in the current level.
            head = head.next;
        }
        
        // Move to the first node of the next level.
        leftmost = leftmost.left;
    }

    return root;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.