Follow up to Problem "populating Next right pointersin each Node".
What if the given tree could is any binary tree? Would your previous solution still work?
Note:
For example,
Given The following binary tree,
1 / 2 3 /\ 4 5 7
After calling your function, the tree is should look like:
1, NULL / 2, 3, null /\ 4-> 5, 7, NULL
Analysis: This is an upgraded version of populating Next right pointers with each node, removing the condition that is perfect binary tree, The effect of removing this condition is that we have to find the next and next level head node of the node P child, the iteration code is as follows:
classSolution { Public: voidConnect (Treelinknode *root) { if(Root = NULL)return; Treelinknode*head =Root; while(head) {Treelinknode*cur =Head; while(cur) {Treelinknode*next = NULL, *p; //Find Next Node for(p = cur->next; p && p->left = = NULL && P->right = = null; p = p->next); if(p = = NULL) Next =NULL; ElseNext = p->left?p->left:p->Right ; //Level Link if(cur->Left ) {cur->left->next = cur->right?cur->Right:next; } if(cur->Right ) cur->right->next =Next; Cur= cur->Next; } //Find Next headTreelinknode *Q; for(q = head; Q && q->left = = NULL && Q->right = = null; q = q->next); if(q = = NULL) head =NULL; ElseHead = q->left?q->left:q->Right ; } }};
The above code is too cumbersome, on the basis of the above code, we simplify, in fact, in each layer, we only need to maintain two variables, a next point to the next layer of the first node, a prev represents the same layer of the previous nodes. The code is as follows:
classSolution { Public: voidConnect (Treelinknode *root) { while(Root) {Treelinknode* next = nullptr;//The first node of next levelTreelinknode * prev = nullptr;//previous node on the same level for(; root; root = root->next) { if(!next) next = Root->left? Root->left:root->Right ; if(root->Left ) { if(prev) Prev->next = root->Left ; Prev= root->Left ; } if(root->Right ) { if(prev) Prev->next = root->Right ; Prev= root->Right ; }} Root= Next;//turn to next level } }};
Leetcode:populating Next Right pointers in each Node II