This question and the previous question populating Next right pointers in each node's not the same, here requires the ordinary tree, the difficulty is relatively big. It was simple to find the left end, and the left-most link on the right. The problem now is that the left and right layers may not be at the leftmost or the same length.
1 / 2 3 /\ 4 5 7
Get:
1, NULL / 2, 3, null /\ 4-> 5, 7, NULL
Assuming that we have to deal with 2 as root, then we have to determine whether 2 of the right subtree exists or not, if there is, 5, then we will be in 2 next sub-tree to find 5 next, that must be 3 of the left subtree priority, but 3 there is no left subtree, so then Judge 3 of the right sub-tree 7, And then 7 as the next 5, imagine, if 3 of the right subtree is also empty, that is not 5 of the next, no, we have to continue to consider whether the next 3 is empty, if 3 's next is not empty, then the 3 next similar to determine whether there are 5 next to the sub-tree. If it's still not there, next to next until you find it, or next is empty.
The next process of 5 must first require 3 to be processed, so the right subtree should be recursive first.
After 5 of next processing, in determining whether 2 of the Zuozi is empty, if it is empty, then return, if not empty, then 5 to 4 Next, if not 5, that is to have just found to give 5 next to 4 as next.
Then you can have:
/** 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) {}}; */classSolution { Public: voidConnect (Treelinknode *root) { if(!root)return ; Treelinknode*p = rootNext; Treelinknode*sonnext =NULL; while(p)//if Next exists, then there may be values that give the root subtree next { if(P-Left ) {Sonnext= P-Left ; Break; } Else if(P-Right ) {Sonnext= P-Right ; Break; } ElseP= P-Next; } if(Root-Right ) {RootRight, Next =Sonnext; if(Root-Left ) RootLeft-to-next = root-Right ; } Else if(Root-Left ) RootLeft-to-next =Sonnext; Connect (Root-Right ); Connect (Root-Left ); }};
Leetcode populating Next right pointers in each Node II