progresivoJS / LeetCode

C++11 Solutions of LeetCode Problems :notebook:
MIT License
0 stars 0 forks source link

Populating Next Right Pointers in Each Node II #2

Closed progresivoJS closed 6 years ago

progresivoJS commented 6 years ago

Find better solution with Space O(1)

progresivoJS commented 6 years ago

https://github.com/progresivoJS/LeetCode/blob/master/C%2B%2B/117.%20Populating%20Next%20Right%20Pointers%20in%20Each%20Node%20II/bfs-with-constant-space.cpp

very tricky.. Tomorrow, I will code again. if success, I'll close this issue.

progresivoJS commented 6 years ago
/**
 * 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) {
        TreeLinkNode* queue = root;
        TreeLinkNode* level = new TreeLinkNode(0);
        while (queue) {
            TreeLinkNode* current = level;
            while (queue) {
                if (queue->left) {
                    current->next = queue->left;
                    current = current->next;
                }
                if (queue->right) {
                    current->next = queue->right;
                    current = current->next;
                }
                queue = queue->next;
            }
            queue = level->next;
            level->next = nullptr;
        }
        delete level;
    }
};

Today I implemented it.