116. Populating Next Right Pointers in Each Node
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
1 2 3 4 5 6 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.
Follow-up:
You may only use constant extra space.
The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
Time : O(hn)
Space : O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 class Solution { pair<bool , Node*> solution (Node* node, int currentLevel, int & targetLevel, Node* prev) { if (!node) return {false , NULL }; if (currentLevel < targetLevel) { auto [resultLeft, leftPrevNode] = solution (node->left, currentLevel + 1 , targetLevel, prev); if (!resultLeft) return {false , NULL }; auto [resultRight, rightPrevNode] = solution (node->right, currentLevel + 1 , targetLevel, leftPrevNode); return {resultRight, rightPrevNode}; } else { if (prev) prev->next = node; return {true , node}; } } public : Node* connect (Node* root) { int level = 1 ; while (true ) { auto [result, _] = solution (root, 0 , level, nullptr ); if (!result) break ; level++; } return root; } };