Populating Next Right Pointers in Each Node in O(1) space (without queue and level order)

Example 1:

Input: root = [1,2,3,4,5,6,7]
Output: [1,#,2,3,#,4,5,6,7,#]
Explanation: Given the above perfect 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: []

class Solution
{
public:
    Node *connect(Node *root)
    {
        Node *p1 = root, *p2;
        while (p1 != NULL)
        {
            p2 = p1;

            while (p2 != NULL)
            {
                if (p2->left)
                    p2->left->next = p2->right;

                if (p2->next && p2->right)
                    p2->right->next = p2->next->left;

                p2 = p2->next;
            }

            p1 = p1->left;
        }
        return root;
    }
};

Comments

Post a Comment

Popular posts from this blog

First_Come_First_Serve CPU Scheduling

Reversing stack Method 2 !! (One Helper Stack only)

Calculate factorial of large numbers !! (Using Arrays)

Multiplication of large numbers (Given in string format)

Left View of Binary Tree (Method 1 using recursion)

Check Bracket Sequence

Image Multiplication

Boundary Traversal of binary tree

BST to greater sum tree