Header Ad

Leetcode Populating Next Right Pointers in Each Node problem solution

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.left.next = root.right
            root.right.next = root.next.left if root.next else None
            self.connect(root.left)
            self.connect(root.right)
        return root



Problem solution in Java.

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


Problem solution in C++.

class Solution {
public:
    Node* connect(Node* root) {
        if(root == NULL){
            return root;
        }
        
        Node* leftmost = root;
        while(leftmost->left!=NULL){
            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)
        return;
    
    while (p) {
        q = p;
        while (q) {
            if (!q->left)
                return;
                
            q->left->next = q->right;
            q->right->next = q->next ? q->next->left : NULL;
            
            q = q->next;
        }
        p = p->left;
    }
}


Post a Comment

0 Comments