https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
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
/** 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) {}}; */classNode { Public: Treelinknode*nd; intLV; Node (Treelinknode* RHS,intl): nd (RHS), LV (l) {}};classSolution { Public: voidConnect (Treelinknode *root) { if(!root)return; Queue<node>Q; Q.push (node (root,0)); Vector<node>VEC; while(!Q.empty ()) {Node Top=Q.front (); Vec.push_back (top); Q.pop (); intCUR_LV =top.lv; Treelinknode* Cur_nd =top.nd; if(cur_nd->left) Q.push (node (cur_nd->left, cur_lv+1)); if(cur_nd->right) Q.push (node (cur_nd->right, cur_lv+1)); } intL =0, r =1; while(R <vec.size ()) {vec[l].nd->next =NULL; while(R < Vec.size () && vec[r].lv = =vec[l].lv) {vec[l].nd->next =vec[r].nd; ++l; ++R; } l=R; R= L +1; } vec[vec.size ()-1].nd->next =NULL; }};
[email protected] [116/117] Populating Next right pointers in each Node I & II (Tree, BFS)