117. Populating Next Right Pointers in Each Node II
Given a binary tree
struct Node { int val; Node *left; Node *right; Node *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
1 2 3
Input: root = [1,2,3,4,5,null,7] Output: [1,#,2,3,#,4,5,7,#] Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
思路
The difference between 116 and 117 is that 117 is not a perfect binary tree, which means it cannot be simply solved by recursive.
The direct way is to use iterative BSF. Note that when reach to null, it’s time to move to the next level and add a nullptr to the end of the queue(for the next level end).
There is a O(1) space complexity way, which is a bit similar to double pointer. The detail is in comments of code. Note the when proceed the current level(currParent), the next has been proceed by last while loop.
classSolution { public: Node* connect(Node* root){ Node *currParent = root; Node *baseChild; Node *currChild; Node *nextChild; while(currParent){ //reach to a parent with at least one child while(currParent->next && !currParent->left && !currParent->right) currParent = currParent->next; //set baseChild and currChild to the first child of the next level currChild = baseChild = currParent->left ? currParent->left : currParent->right; while(currChild){ //if currChild is left child and have right sibling if(currParent->right && currParent->right != currChild){ nextChild = currParent->right; } else{ //move to the adjacent parent currParent = currParent->next; while(currParent && !currParent->left && !currParent->right){ currParent = currParent->next; //now currParent has pointed to the next Parent } //if not reach to the end if(currParent){ nextChild = currParent->left ? currParent->left : currParent->right; } //if reach to the end else{ //if reach to the end of this level nextChild = nullptr; } } currChild->next = nextChild; currChild = nextChild; } //move to the next level currParent = baseChild; } return root; } };