In this Leetcode Populating Next Right Pointers in Each Node problem solution we have given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:

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.

Leetcode Populating Next Right Pointers in Each Node problem solution

Problem solution in Python.

if root and root.left:
   = root.right
   = if else None
        return root

Problem solution in Java.

public void connect(TreeLinkNode root) {
    private void dfs(TreeLinkNode root){
        if(root == null ||(root.left == null && root.right == null)) return; = root.right;
        if( != null) =;

Problem solution in C++.

class Solution {
    Node* connect(Node* root) {
        if(root == NULL){
            return root;
        Node* leftmost = root;
            Node* cur = leftmost;
            Node* prev = NULL;
            while(cur != NULL){
                cur->left->next = cur->right;
                if(prev != NULL){
                    prev->right->next = cur->left;
                prev = cur;
                cur = cur->next;
            leftmost = leftmost->left;
        return root;

Problem solution in C.

void connect(struct TreeLinkNode *root) {
    struct TreeLinkNode *p = root, *q;
    if (!root)
    while (p) {
        q = p;
        while (q) {
            if (!q->left)
            q->left->next = q->right;
            q->right->next = q->next ? q->next->left : NULL;
            q = q->next;
        p = p->left;