Populating Next Right Pointers in Each Node II [Leetcode]
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".
1 /** 2 * Definition for binary tree with next pointer. 3 * struct TreeLinkNode { 4 * int val; 5 * TreeLinkNode *left, *right, *next; 6 * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 void connect(TreeLinkNode *root) { 12 // Start typing your C/C++ solution below 13 // DO NOT write int main() function 14 if(root == NULL) 15 return; 16 if(root->left == NULL && root->right == NULL){ 17 root->next = NULL; 18 return; 19 } 20 21 vector<TreeLinkNode *> nodes_previous_level; 22 nodes_previous_level.push_back(root); 23 24 while(true) { 25 vector<TreeLinkNode *> nodes_current_level; 26 for(auto item: nodes_previous_level) { 27 if(item->left != NULL) 28 nodes_current_level.push_back(item->left); 29 if(item->right != NULL) 30 nodes_current_level.push_back(item->right); 31 } 32 33 if(nodes_current_level.size() == 0) 34 break; 35 36 //connect 37 for(int j =0; j< nodes_current_level.size(); j++) { 38 if(j+1 == nodes_current_level.size()) 39 nodes_current_level[j]->next = NULL; 40 else 41 nodes_current_level[j]->next = nodes_current_level[j + 1]; 42 43 } 44 45 nodes_previous_level.clear(); 46 nodes_previous_level = nodes_current_level; 47 } 48 49 return; 50 } 51 };