[Problem]
[Solution]
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
[Solution]
class Solution {说明:版权所有,转载请注明出处。 Coder007的博客
public:
void connect(TreeLinkNode *root) {
// Note: The Solution object is instantiated only once and is reused by each test case.
// null node
if(NULL == root)return;
// initial
queue<vector<TreeLinkNode*> > myQueue;
vector<TreeLinkNode*> head;
head.push_back(root);
myQueue.push(head);
// BFS
while(!myQueue.empty()){
vector<TreeLinkNode*> row = myQueue.front();
myQueue.pop();
// visit the first
vector<TreeLinkNode*> next;
TreeLinkNode* pre = row[0];
if(pre->left != NULL){
next.push_back(pre->left);
}
if(pre->right != NULL){
next.push_back(pre->right);
}
// visit the remain
for(int i = 1; i < row.size(); ++i){
pre->next = row[i];
if(row[i]->left != NULL){
next.push_back(row[i]->left);
}
if(row[i]->right != NULL){
next.push_back(row[i]->right);
}
pre = row[i];
}
// enqueue
if(next.size() > 0)myQueue.push(next);
}
}
};