Leetcode Populating Next Right Pointers in Each Node II
This question is different from the previous question Populating Next Right Pointers in Each Node. The requirement here is a common tree, which is more difficult. Previously, we simply found the last link on the left and the leftmost link on the right. The problem is that the Left and Right layers on the right are not at the left or have different lengths. 1/\ 2 3/\ 4 5 7 get: 1-> NULL/\ 2-> 3-> NULL/\ 4-> 5-> 7-> NULL assume that when processing 2 as root, then we need to judge whether the right subtree of 2 exists or not. If so, in the example of 5, we need to find the next of 5 in the subtree of next of 2, it must be the left subtree of 3, but 3 does not have the left subtree, so I will judge the right subtree of 3 7, and then take 7 as the next of 5. Imagine, if the right subtree of 3 is empty, is there no next of 5? No, we still need to consider whether the next of 3 is empty. If the next of 3 is not empty, then we will judge the Left and Right Subtrees of 3 to see if there are any next matching with 5. If there is still no, the next is the next until it is found, or the next is null. In the next processing process of Step 5, step 3 is required to be processed. Therefore, the right subtree should be recursive first. After processing next in step 5, check whether the left subtree of step 2 is null. If it is null, return the result. If it is not empty, then the next of Step 5 to Step 4 is returned, if there is no 5, it is to give 4 next, which was originally set to 5, as next. Then you can copy the code/*** 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) {}*}; */class Solution {public: void connect (TreeLinkNode * root) {if (! Root) return; TreeLinkNode * p = root-> next; TreeLinkNode * sonNext = NULL; while (p) // If next exists, then there may be a value for the next {if (p-> left) {sonNext = p-> left; break;} else if (p-> right) of the root subtree) {sonNext = p-> right; break;} else p = p-> next;} if (root-> right) {root-> right-> next = sonNext; if (root-> left) root-> left-> next = root-> right;} else if (root-> left) root-> left-> next = sonNext; connect (root-> right); connect (root-> left );}