117. Populating Next Right Pointers in Each Node II
Last updated
Was this helpful?
Last updated
Was this helpful?
Given a binary tree
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.
Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.
Example 1:
Constraints:
The number of nodes in the given tree is less than 6000
.
-100 <= node.val <= 100
Tree, Breadth-first Search
You can still use the solution in LeetCode 116. However, there is a O(1) space complexity solution.
We can connect nodes in the next level from the current level. We use a pointer last
to traverse and connect all nodes in the next level starting from the first node in the next level. Also, we initialize a pointer nextStart
to indicate the first node in the next level.
Traverse the current level, we process the left and right children (if exists) of each node. If last
is not null, we assign the current child node to its Next, and move last
to this child node. If nextStart
is null, we assign the first child node to it as the first node in the next level. After processing all nodes in the current level, we begin to process from nextStart
, only if it is not null.
Time complexity:
Space complexity: