【second】Populating Next Right Pointers in Each Node II
问题的本质就是:树的level-order遍历
TreeLinkNode* getNextSibling(TreeLinkNode* cur) { while(cur) { if(cur->left) return cur->left; if(cur->right) return cur->right; cur = cur->next; } return NULL; } class Solution { public: void connect(TreeLinkNode *root) { // Note: The Solution object is instantiated only once and is reused by each test case. TreeLinkNode* first,*cur; first = root; while(first) { cur = first; while(cur) { if(cur->left&&cur->right) { cur->left->next = cur->right; cur->right->next = getNextSibling(cur->next); }else if(cur->left&&!cur->right) { cur->left->next = getNextSibling(cur->next); }else if(!cur->left&&cur->right) { cur->right->next = getNextSibling(cur->next); } cur = cur->next; } if(first->left) first = first->left; else if(first->right) first = first->right; else first = getNextSibling(first->next); } } };
上述解法有大量重复。主要集中在getNextSibling。
void connect(TreeLinkNode *root) { // Note: The Solution object is instantiated only once and is reused by each test case. TreeLinkNode* first,*cur; first = root; while(first) { TreeLinkNode* nextFirst = NULL; //start node of next level TreeLinkNode* prev = NULL; //prev node of cur level cur = first; while(cur) { if(!nextFirst) nextFirst = (cur->left?cur->left:cur->right); if(cur->left) { if(prev) prev->next = cur->left; prev = cur->left; } if(cur->right) { if(prev) prev->next = cur->right; prev = cur->right; } cur = cur->next; } first = nextFirst; } }