Closed progresivoJS closed 6 years ago
very tricky.. Tomorrow, I will code again. if success, I'll close this issue.
/**
* 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.
Find better solution with Space O(1)