Thursday, February 19, 2015

Populating Next Right Pointers in Each Node

Populating Next Right Pointers in Each Node
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 to NULL.
Initially, all next pointers are set to NULL.
Note:
  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,
         1
       /  \
      2    3
     / \  / \
    4  5  6  7
After calling your function, the tree should look like:
         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \  / \
    4->5->6->7 -> NULL

----------------- thinking ------------------
I'm using stack, there is a method that no stack is needed, please read codes
https://oj.leetcode.com/discuss/21343/a-concise-o-1-space-complexity-solution

------------------ codes ---------------------
class Solution {
public:
    void connect(TreeLinkNode *root) {
        queue<TreeLinkNode *> queue;
        if (root == NULL) {
            return;
        }
        queue.push(root);
        queue.push(NULL);
        while (queue.size() > 1) {
            TreeLinkNode *cur = queue.front();
            queue.pop();
            if (cur == NULL) {
                queue.push(NULL);
                continue;
            }
            //if (queue.size()>1) {
                if (cur->left) {
                    queue.push(cur->left);
                }
                if (cur->right) {
                    queue.push(cur->right);
                }
                if (queue.front() == NULL) {
                    cur->next = NULL;
                } else {
                    cur->next = queue.front();
                }
            //}
        }
    }
};

------------------ read codes -----------------
void connect(TreeLinkNode *root) { TreeLinkNode *head = root; // the left first node in every level TreeLinkNode *cur = NULL; // the current node in the upper level TreeLinkNode *pre = NULL; // the prev node in the downer level while (head) { cur = head; head = pre = NULL; // travel one level in a loop while (cur) { // left child exist if (cur->left) { if (pre) pre = pre->next = cur->left; else head = pre = cur->left; } // right child exist if (cur->right) { if (pre) pre = pre->next = cur->right; else head = pre = cur->right; } // next node in the same level cur = cur->next; } } }

No comments:

Post a Comment