Problem Description http://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
Basic idea is to get every nodes in the current level by iterating nodes of the previous level, then to iterate all nodes in current level to connect them with pointer "next".
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(root == NULL)
return;
if(root->left == NULL && root->right == NULL){
root->next = NULL;
return;
} vector<TreeLinkNode *> nodes_previous_level;
nodes_previous_level.push_back(root); while(true) {
vector<TreeLinkNode *> nodes_current_level;
for(auto item: nodes_previous_level) {
if(item->left != NULL)
nodes_current_level.push_back(item->left);
if(item->right != NULL)
nodes_current_level.push_back(item->right);
} if(nodes_current_level.size() == )
break; //connect
for(int j =; j< nodes_current_level.size(); j++) {
if(j+ == nodes_current_level.size())
nodes_current_level[j]->next = NULL;
else
nodes_current_level[j]->next = nodes_current_level[j + ]; } nodes_previous_level.clear();
nodes_previous_level = nodes_current_level;
} return;
}
};