Friday, January 11, 2013

Populating Next Right pointers in each node

Problem:

Given a binary tree
    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *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 toNULL.
Initially, all next pointers are set to NULL.

Solution:

/**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  TreeLinkNode *left, *right, *next;
 *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 * };
 */
class Solution {
public:
    void connect(TreeLinkNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (root == NULL) {
            return;
        }
        queue<TreeLinkNode *> queueTree;
        TreeLinkNode *popedNode;
     
        queueTree.push(root);
     
        while (!queueTree.empty()) {
            popedNode = queueTree.front();
            queueTree.pop();
         
            if (popedNode->left) {
                popedNode->left->next = popedNode->right;
                queueTree.push(popedNode->left);
            }
            if (popedNode->right) {
                popedNode->right->next = (popedNode->next == NULL ? NULL : popedNode->next->left);
                queueTree.push(popedNode->right);
            }
        }
        return;
    }
};

==============
class Solution {
    public Node connect(Node root) {
       
        if (root == null) {
            return root;
        }
       
        // Start with the root node. There are no next pointers
        // that need to be set up on the first level
        Node leftmost = root;
       
        // Once we reach the final level, we are done
        while (leftmost.left != null) {
           
            // Iterate the "linked list" starting from the head
            // node and using the next pointers, establish the
            // corresponding links for the next level
            Node head = leftmost;
           
            while (head != null) {
               
                // CONNECTION 1
                head.left.next = head.right;
               
                // CONNECTION 2
                if (head.next != null) {
                    head.right.next = head.next.left;
                }
               
                // Progress along the list (nodes on the current level)
                head = head.next;
            }
           
            // Move onto the next level
            leftmost = leftmost.left;
        }
       
        return root;
    }
}

No comments:

Post a Comment