Test instructions
To a tree full of two, requires that each layer of the node from left to right with the next pointer, the end of the layer pointing to null.
Ideas:
can be recursive or iterative. It is necessary to observe that Next's left child happens to be next to the right child of this node.
(1) Recursion: This is faster.
1 /**2 * Definition for binary tree with next pointer.3 * struct Treelinknode {4 * int val;5 * Treelinknode *left, *right, *next;6 * Treelinknode (int x): Val (x), left (null), Right (null), Next (null) {}7 * };8 */9 classSolution {Ten Public: One voidDFS (treelinknode* root,treelinknode*t) A { - if(Root->next==null && t!=null) root->next=t->Left ; - if(root->Left ) the { -Root->left->next=root->Right ; -DFS (root->Left , NULL); -DFS (root->right,root->next); + } - } + voidConnect (Treelinknode *root) { A if(Root) DFS (root,null); at } -};
AC Code
(2) Recursion: this brevity.
1 /**2 * Definition for binary tree with next pointer.3 * struct Treelinknode {4 * int val;5 * Treelinknode *left, *right, *next;6 * Treelinknode (int x): Val (x), left (null), Right (null), Next (null) {}7 * };8 */9 classSolution {Ten Public: One voidConnect (Treelinknode *root) { A if(Root && root->Left ) - { -Root->left->next=root->Right ; the if(root->next) -Root->right->next=root->next->Left ; -Connect (root->Left ); -Connect (root->Right ); + } - + A } at};
AC Code
(3) Iteration: This is more hanging.
Leetcode populating Next right pointers in each Node (tips)