Topic:
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
Idea: And the above question is similar, just need to slowly find, update the time also need to slowly find
void order (bintree* root) {bintree* temp = root; bintree* next_head = NULL; if (temp = = NULL) return; while (temp! = NULL) {cout<<temp->value<<endl; temp = temp->next; } temp = root; while (temp! = null) {if (temp->left! = null) {next_head= temp->left; Break } if (Temp->right!=null) {next_head = temp->right; Break } temp = temp->next; } order (next_head);} Pre_head has always been the first node of the previous layer void Helper_third (bintree* pre_head) {bintree* pre = Pre_head; Bintree* Cur_first=null; Bintree* Cur_second=null; Bintree* Next_head=null; while (pre! = null && (Cur_first = = NULL | | cur_second = = NULL)) {if (pre->left! = null) { if (Cur_first = = NULL) {cur_first= pre->left; Next_head = Cur_first; } elseif (Cur_second ==null) Cur_second = pre->left; if (pre->right! = null) {if (Cur_first = = null) {Cur_first = pre->right; Next_head = Cur_first; } else if (Cur_second = = NULL) Cur_second = pre->right; } if (Cur_first! = NULL && Cur_second! = null) break; Pre = pre->next; } if (Cur_first = = NULL && Cur_second = = null) return; while (pre! = NULL) {cur_first->next = Cur_second; Cur_first = Cur_second; if (Cur_second = = Pre->left && pre->right! = NULL) {Cur_second = pre->right; Continue } pre = pre->next; while (pre! = null) {if (pre->left! = null) {Cur_second = pre->left; Break } if (pre->right! = NULL) {Cur_second = pre->right; Break } pre = pre->next; }} if (Cur_first! = null) Cur_first->next = NULL; Helper_third (Next_head);} void Connect_third (bintree* root) {if (root==null) return; Root->next = NULL; Helper_third (root); }
Populating Next right pointers in each Node Ii--leetcode