At first glance it's hard, and it's easy to sort out your ideas.
/** * Definition for binary tree with next pointer. * struct Treelinknode {* int val; * Treelinknode *left, *right, *next; * treelinknode (int x): Val (x), left (N ULL), right (null), Next (null) {} *}; */class Solution {public: void Connect (Treelinknode *root) { if (root==null| | Root->left==null) return; root->left->next=root->right; if (root->next!=null) root->right->next=root->next->left; Connect (root->left); Connect (root->right); return;} };
II: and girlfriend to make a contradiction, the mood is not very good, there is no self-written, directly see the online.
/** * Definition for binary tree with next pointer. * struct Treelinknode {* int val; * Treelinknode *left, *right, *next; * Treelinknode (int x): Val (x), left (NULL), rig HT (NULL), Next (null) {}}; */class Solution {public:void Connect (Treelinknode *root) {if (NULL = = root) return; treelinknode* start; treelinknode* Curnode; Treelinknode* NextNode; while (root = NULL) {start = Findstartnodenextlev (root); Curnode = start; NextNode = Findnextnodenextlev (root, start); while (nextnode! = NULL) {curnode, next = NextNode; Curnode = NextNode; NextNode = Findnextnodenextlev (root, Curnode); } root = start; }}private:treelinknode* Findnextnodenextlev (treelinknode* &cur, treelinknode* CurNextLev) {if (cur- left = = Curnextlev && cur, right! = NULL) {return cur, right; }else{while (cur-next! = NULL) {cur = cur-next; if (cur, left! = NULL && cur, left! = Curnextlev) return cur, left; if (cur, right! = NULL && cur, right! = Curnextlev) return cur, right; }} return NULL; } treelinknode* Findstartnodenextlev (treelinknode* node) {if (Null = = node) return null; if (node-to-Left! = NULL) return node, left; Return Findnextnodenextlev (node, node-to-left); }};
Populating Next right pointers in each Node I II