Problem:
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
- You may only use constant extra space.
For example,
Given the following binary tree,
1 / \ 2 3 / \ \ 4 5 7
After calling your function, the tree should look like:
1 -> NULL / \ 2 -> 3 -> NULL / \ \ 4-> 5 -> 7 -> NULL
Analysis:
The non-recursive solution of 116 can be directly used in this solution. This is because that solution first group nodes by level and then populate the next pointer of each pointer.
Solutions:
C++:
void connect(TreeLinkNode *root) {
if(root == NULL || (root->left == NULL && root->right == NULL))
return;
queue<TreeLinkNode *> node_queue;
node_queue.push(NULL);
TreeLinkNode *p_cur = root;
vector<TreeLinkNode *> node_level;
while(p_cur || !node_queue.empty()) {
if(p_cur) {
if(p_cur->left) {
node_queue.push(p_cur->left);
node_level.push_back(p_cur->left);
}
if(p_cur->right) {
node_queue.push(p_cur->right);
node_level.push_back(p_cur->right);
}
} else {
node_queue.push(NULL);
for(int i = 0; i < node_level.size() - 1; ++i)
node_level[i]->next = node_level[i + 1];
node_level.clear();
}
p_cur = node_queue.front();
node_queue.pop();
}
}
Java
:
Python: